package com.toycloud.business.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.toycloud.business.dto.params.*;
import com.toycloud.business.dto.results.CommonResult;
import com.toycloud.business.dto.results.FeedbackAnalysisResult;
import com.toycloud.business.dto.results.FeedbackRecordResult;
import com.toycloud.business.dto.results.FeedbackRecordResultVo;
import com.toycloud.business.service.IFeedbackConfigService;
import com.toycloud.business.service.IUserFeedBackService;
import com.toycloud.common.core.utils.StringUtils;
import com.toycloud.system.domain.dto.AnalysisDetailDTO;
import com.toycloud.system.domain.dto.FeedbackUserLabelRecordDTO;
import com.toycloud.system.domain.feedback.FeedbackAnalysisData;
import com.toycloud.system.domain.feedback.FeedbackConfig;
import com.toycloud.system.domain.dto.FeedbackLabelDTO;
import com.toycloud.system.domain.feedback.FeedbackRecord;
import com.toycloud.system.domain.feedback.FeedbackUserLabelRecord;
import com.toycloud.system.mapper.feedback.FeedbackAnalysisDataMapper;
import com.toycloud.system.mapper.feedback.FeedbackConfigMapper;
import com.toycloud.system.mapper.feedback.FeedbackRecordMapper;
import com.toycloud.system.mapper.feedback.FeedbackUserLabelRecordMapper;
import com.toycloud.system.utils.Dictionary;
import com.toycloud.system.utils.ExcelDealUtil;
import com.toycloud.system.utils.OnesUtil;
import com.toycloud.system.utils.Openstorage;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author xqyang5
 * @Date 2024/9/18 18:00
 */
@Slf4j
@Service
public class UserFeedBackServiceImpl implements IUserFeedBackService {
    //    private static final Logger log = LoggerFactory.getLogger(UserFeedBackServiceImpl.class);
    @Autowired
    private FeedbackRecordMapper feedbackRecordMapper;
    @Autowired
    private FeedbackConfigMapper feedbackConfigMapper;
    @Autowired
    private FeedbackUserLabelRecordMapper feedbackUserLabelRecordMapper;
    @Autowired
    private IFeedbackConfigService feedbackConfigService;
    @Autowired
    private FeedbackAnalysisDataMapper feedbackAnalysisDataMapper;
    @Autowired
    private Openstorage openstorage;

    private static final String BASE_DIRECTORY = System.getProperty("user.dir");
    private static final String IMAGE_PATH = BASE_DIRECTORY + File.separator + "img" + File.separator;
    private static final String EXCEL_PATH = BASE_DIRECTORY + File.separator + "excel" + File.separator;
    private static final String EXPORT_EXCEL_PATH = BASE_DIRECTORY + File.separator + "excel" + File.separator + "export" + File.separator;

    public FeedbackRecordSearchParams assmbleSearchParam(FeedbackRecordParams params) {
        //构造查询参数
        FeedbackRecordSearchParams searchParam = new FeedbackRecordSearchParams()
                .setId(params.getId())
                .setBrand(params.getBrand())
                .setCategory(params.getCategory())
                .setProduct(params.getProduct())
                .setFeedbackStep(params.getFeedbackStep())
                .setFeedbackSource(params.getFeedbackSource())

                .setBrandArr(params.getBrandArr())
                .setCategoryArr(params.getCategoryArr())
                .setProductArr(params.getProductArr())
                .setStepArr(params.getStepArr())
                .setSourceArr(params.getSourceArr())
                .setReadMarkArr(params.getReadMarkArr())
                .setFeedbackTypeArr(params.getFeedbackTypeArr())
                .setUserAttitudeArr(params.getUserAttitudeArr())

                .setReadMark(params.getReadMark())
                .setSortField(convertCamelToSnake(params.getSortField()))
                .setSortOrder(params.getSortOrder())
                .setFeedbackContent(params.getFeedbackContent())
                .setOriginalContent(params.getOriginalContent())
                .setFeedbackType(params.getFeedbackType())
                .setBeginTime(params.getBeginTime())
                .setEndTime(params.getEndTime())
                .setCurrent(params.getCurrent())
                .setPageSize(params.getPageSize())
                .setSearch(params.getSearch())
                .setCascaderLabelIds(params.getCascaderLabelIds());
        return searchParam;
    }

    public FeedbackRecordSearchParams assmbleSearchParamVo(FeedbackRecordParams params) {
        //构造查询参数
        FeedbackRecordSearchParams searchParam = new FeedbackRecordSearchParams()
                .setId(params.getId())
                .setBrand(params.getBrand())
                .setCategory(params.getCategory())
                .setProduct(params.getProduct())
                .setFeedbackStep(params.getFeedbackStep())
                .setFeedbackSource(params.getFeedbackSource())

                .setBrandArr(params.getBrandArr())
                .setCategoryArr(params.getCategoryArr())
                .setProductArr(params.getProductArr())
                .setStepArr(params.getStepArr())
                .setSourceArr(params.getSourceArr())
                .setReadMarkArr(params.getReadMarkArr())
                .setFeedbackTypeArr(params.getFeedbackTypeArr())
                .setUserAttitudeArr(params.getUserAttitudeArr())

                .setReadMark(params.getReadMark())
                .setSortField(convertCamelToSnake(params.getSortField()))
                .setSortOrder(params.getSortOrder())
                .setFeedbackContent(params.getFeedbackContent())
                .setOriginalContent(params.getOriginalContent())
                .setFeedbackType(params.getFeedbackType())
                .setBeginTime(params.getBeginTime())
                .setEndTime(params.getEndTime())
                .setSearch(params.getSearch())
                .setCascaderLabelIds(params.getCascaderLabelIds());
        return searchParam;
    }

    public static String convertCamelToSnake(String camelCaseStr) {
        if (camelCaseStr == null || camelCaseStr.isEmpty()) {
            return camelCaseStr;
        }

        StringBuilder result = new StringBuilder();
        result.append(Character.toLowerCase(camelCaseStr.charAt(0)));

        for (int i = 1; i < camelCaseStr.length(); i++) {
            char ch = camelCaseStr.charAt(i);
            if (Character.isUpperCase(ch)) {
                result.append('_').append(Character.toLowerCase(ch));
            } else {
                result.append(ch);
            }
        }

        return result.toString();
    }

    @Override
    public CommonResult<List<FeedbackRecordResult>> getFeedbackRecordList(FeedbackRecordParams params) {
        List<FeedbackRecordResult> resultList = new LinkedList<>() ;
        FeedbackRecordResult outRecord = null;
        PageHelper.startPage(params.getCurrent(), params.getPageSize());
        Page<FeedbackRecord> feedbackRecordList = feedbackRecordMapper.selectByParams(assmbleSearchParam(params));

        // 获取 FeedbackUserAttitudeParam 列表
        List<FeedbackUserAttitudeParam> feedbackUserAttitudeParams = Optional.ofNullable(params.getFeedbackUserAttitudeParam())
                .orElse(Collections.emptyList());
        Page<FeedbackRecord> filteredRecords ;
        if (!feedbackUserAttitudeParams.isEmpty()) {
            Page<FeedbackRecord> feedbackRecordList1 = feedbackRecordMapper.selectByParams(assmbleSearchParamVo(params));
            // 创建一个新的 Page 对象，用于存储过滤后的结果
            filteredRecords = new Page<>();
            filteredRecords.setPageNum(feedbackRecordList1.getPageNum()); // 设置当前页码
            filteredRecords.setPageSize(feedbackRecordList1.getPageSize()); // 设置每页大小


            // 遍历原始分页数据，进行过滤
            for (FeedbackRecord record : feedbackRecordList1) {
                // 检查 labelIds 和 userAttitude 是否为 null 或空
                if (record.getLabelIds() == null || record.getLabelIds().trim().isEmpty() ||
                        record.getUserAttitude() == null || record.getUserAttitude().trim().isEmpty()) {
                    continue; // 跳过该记录
                }

                // 解析 labelIds
                String[] labelIds = record.getLabelIds().split(",");
                // 解析 userAttitude
                String[] userAttitudes = record.getUserAttitude().split(",");

                // 遍历 feedbackUserAttitudeParams，检查是否有任意一个对象满足条件
                boolean match = false;
                for (FeedbackUserAttitudeParam param : feedbackUserAttitudeParams) {
                    // 获取 cascaderLabelIds 和 userAttitudeArr
                    String queryCascaderLabelId = param.getCascaderLabelIds();
                    Integer queryUserAttitude = param.getUserAttitudeArr();

                    // 检查是否有相同索引位置满足条件
                    for (int i = 0; i < labelIds.length && i < userAttitudes.length; i++) {

                        String labelId = labelIds[i];
                        // 检查 labelId 是否为 null 或空字符串
                        if (labelId == null || labelId.trim().isEmpty()) {
                            continue; // 跳过该条目
                        }
                        // 检查 userAttitudes[i] 是否为 null 或空字符串
                        if (userAttitudes[i] == null || userAttitudes[i].trim().isEmpty()) {
                            continue; // 跳过该条目
                        }
                        // 解析为整数
                        int userAttitude = Integer.parseInt(userAttitudes[i]);

                        // 检查 labelId 和 userAttitude 是否分别与 cascaderLabelIds 和 userAttitudeArr 的相同索引位置的值相同
                        if (Objects.equals(labelId, queryCascaderLabelId) &&
                                userAttitude == queryUserAttitude) {
                            match = true;
                            break; // 匹配成功，跳出循环
                        }
                    }
                    if (match) {
                        break; // 匹配成功，跳出循环
                    }
                }

                // 如果匹配成功，将记录添加到过滤后的 Page 对象中
                if (match) {
                    filteredRecords.add(record);
                }
            }
            filteredRecords.setTotal(filteredRecords.getTotal()); // 设置总记录数
        } else {
            // 如果没有过滤条件，直接使用原始分页结果
            filteredRecords = feedbackRecordList;
            filteredRecords.setTotal(feedbackRecordList.getTotal()); // 设置总记录数
        }

        // 筛选符合条件的记录

        Page<FeedbackRecord> feedbackRecordPage = (Page<FeedbackRecord>) filteredRecords;

        //配置
        String configIds = filteredRecords.stream()
                .filter(x->StringUtils.isNotEmpty(x.getConfigIds()))
                .map(FeedbackRecord::getConfigIds)
                .collect(Collectors.joining(","));
        String userLabelIds = filteredRecords.stream()
                .filter(x -> StringUtils.isNotEmpty(x.getUserLabelIds()))
                .map(FeedbackRecord::getUserLabelIds)
                .collect(Collectors.joining(","));
        String labelIds = null;
        List<FeedbackUserLabelRecord> userLabelList = new ArrayList<>();
        if (StringUtils.isNotEmpty(userLabelIds)) {
            userLabelList = feedbackUserLabelRecordMapper.selectUserLabelByIds(userLabelIds.split(","));
            labelIds = userLabelList.stream()
                    .filter(x -> x.getLabelId() != null)
                    .map(x -> x.getLabelId().toString())
                    .collect(Collectors.joining(","));
        }
        //标签
        if (StringUtils.isNotEmpty(labelIds)) {
            configIds = configIds + "," + labelIds;
        }

        String[] typeArr = {"5", "6", "7","9"};
        List<FeedbackConfig> labelConfigList = feedbackConfigMapper.selectByTypes(typeArr);
        List<FeedbackConfig> configList = feedbackConfigMapper.selectByIds(configIds.split(","));
        int i = 0;
        long prevId = 0;
        long nextId = 0;
        for (FeedbackRecord feedbackRecord : filteredRecords) {
            outRecord = new FeedbackRecordResult();
            //上一个下一个
            if (i == 0) {
                prevId = 0;
            } else {
                prevId = filteredRecords.get(i - 1).getId();
            }

            if (i == filteredRecords.size() - 1) {
                nextId = 0;
            } else {
                nextId = filteredRecords.get(i + 1).getId();
            }
            i++;

            //相同属性赋值
            BeanUtils.copyProperties(feedbackRecord, outRecord);
            if(feedbackRecord.getFileList()!=null && !feedbackRecord.getFileList().isEmpty()){
                outRecord.setFileList( Arrays.asList(feedbackRecord.getFileList().split(",,,,")));
            }else{
                outRecord.setFileList(new ArrayList<>());
            }
            outRecord.setConsultCount(outRecord.getConsultCount() == 0 ? null : outRecord.getConsultCount());
            outRecord.setLikeCount(outRecord.getLikeCount() == 0 ? null : outRecord.getLikeCount());
            outRecord.setViewCount(outRecord.getViewCount() == 0 ? null : outRecord.getViewCount());
            List<FeedbackConfig> currentConfigList = configList.stream()
                    .filter(x ->
                            Arrays.stream(feedbackRecord.getConfigIds().split(",")).anyMatch(y -> y.equals(x.getId().toString()))
                    )
                    .sorted(Comparator.comparing(x -> (String) x.getType()))
                    .collect(Collectors.toList());
            List<FeedbackUserLabelRecord> currentUserLabelList = userLabelList.stream()
                    .filter(x ->
                            Arrays.stream(feedbackRecord.getUserLabelIds().split(",")).anyMatch(y -> y.equals(x.getId().toString()))
                    )
                    .collect(Collectors.toList());
            //构造
            List<FeedbackUserLabelRecordDTO> currentUserLabelDTOList = new ArrayList<>();
            currentUserLabelList.forEach(x -> {
                //ones工单状态获取
                String ticketStatusName = null;
                if (StringUtils.isNotEmpty(x.getTicketStatus())) {
                    OnesUtil.TaskStatuses taskStatuses = OnesUtil.getTaskStatuses(TEAM_UUID);
                    if (taskStatuses != null) {
                        Optional<OnesUtil.StatuDetail> optional = taskStatuses.getTask_statuses().stream()
                                .filter(y -> y.getUuid().equals(x.getTicketStatus()))
                                .findFirst();
                        if (optional.isPresent()) {
                            ticketStatusName = optional.get().getName();
                        }
                    }
                }
                FeedbackUserLabelRecordDTO dto = new FeedbackUserLabelRecordDTO();
                BeanUtils.copyProperties(x, dto);
                if(x.getProblemId()!=null){
                    FeedbackConfig problemConfig = labelConfigList.stream().
                            filter(y -> y.getId().equals(x.getProblemId()))
                            .findFirst()
                            .orElse(null);
                    if(problemConfig!=null){
                        dto.setProblemName(problemConfig.getName());
                    }
                }
                FeedbackConfig threeLabelConfig = labelConfigList.stream().
                        filter(y -> y.getId().equals(x.getLabelId()))
                        .findFirst()
                        .orElse(null);
                if (threeLabelConfig != null) {
                    dto.setLabelId(threeLabelConfig.getId());
                    dto.setThreeLevelLabel(threeLabelConfig.getName());
                    //查找一二级节点
                    FeedbackConfig secondLevelLabelConfig = labelConfigList.stream()
                            .filter(y -> y.getId().equals(threeLabelConfig.getPid()))
                            .findFirst()
                            .orElse(null);
                    if (secondLevelLabelConfig != null) {
                        dto.setSecondLevelLabel(secondLevelLabelConfig.getName());
                        FeedbackConfig firstLevelLabelConfig = labelConfigList.stream()
                                .filter(y -> y.getId().equals(secondLevelLabelConfig.getPid()))
                                .findFirst()
                                .orElse(null);
                        if (firstLevelLabelConfig != null) {
                            dto.setFirstLevelLabel(firstLevelLabelConfig.getName());
                        }
                        dto.setTicketStatusName(ticketStatusName);
                        currentUserLabelDTOList.add(dto);
                    }
                }
            });
            List<FeedbackLabelDTO> currentLabelList = new ArrayList<>();
            //构造
            for (FeedbackUserLabelRecordDTO dto : currentUserLabelDTOList) {
                FeedbackLabelDTO label = new FeedbackLabelDTO();
                BeanUtils.copyProperties(dto, label);
                label.setId(dto.getLabelId());
                currentLabelList.add(label);
            }
            outRecord.setFeedbackContent(feedbackRecord.getFeedbackContent())
                    .setFeedbackConfigList(currentConfigList)
                    .setUserLabels(currentUserLabelDTOList)
                    .setCascaderLabels(generateCascaderLabel(currentLabelList))
                    .setPrevId(prevId)
                    .setNextId(nextId)
                    .setReadMark(String.valueOf(feedbackRecord.getReadMark()));
            if (params.getId() != 0) {
                if (params.getId().equals(feedbackRecord.getId())) {
                    resultList.add(outRecord);
                }
            } else {
                resultList.add(outRecord);
            }
        }
        return CommonResult.Success((int) feedbackRecordPage.getTotal(), resultList);
    }

    @Override
    public List<FeedbackRecordResultVo> getFeedbackRecordVO(FeedbackRecordParams params) {
        List<FeedbackRecordResultVo> resultList = new LinkedList<>() ;
        FeedbackRecordResultVo outRecord = null;
        List<FeedbackRecord> feedbackRecordList = new ArrayList<>();
        feedbackRecordList = feedbackRecordMapper.selectByParams(assmbleSearchParamVo(params));

        // 获取 FeedbackUserAttitudeParam 列表
        List<FeedbackUserAttitudeParam> feedbackUserAttitudeParams = Optional.ofNullable(params.getFeedbackUserAttitudeParam())
                .orElse(Collections.emptyList());
        List<FeedbackRecord> filteredRecords = new ArrayList<>();
        if(!feedbackUserAttitudeParams.isEmpty()){
            filteredRecords = feedbackRecordList.stream()
                    .filter(record -> {
                        // 检查 labelIds 和 userAttitude 是否为 null 或空
                        if (record.getLabelIds() == null || record.getLabelIds().trim().isEmpty() ||
                                record.getUserAttitude() == null || record.getUserAttitude().trim().isEmpty()) {
                            return false; // 跳过该记录
                        }
                        // 解析 labelIds
                        String[] labelIds = record.getLabelIds().split(",");
                        // 解析 userAttitude
                        String[] userAttitudes = record.getUserAttitude().split(",");

                        // 遍历 feedbackUserAttitudeParams，检查是否有任意一个对象满足条件
                        for (FeedbackUserAttitudeParam param : feedbackUserAttitudeParams) {


                            // 获取 cascaderLabelIds 和 userAttitudeArr
                            String queryCascaderLabelId = param.getCascaderLabelIds();

                            Integer queryUserAttitude = param.getUserAttitudeArr();

                            // 检查是否有相同索引位置满足条件
                            for (int i = 0; i < labelIds.length && i < userAttitudes.length; i++) {
                                String labelId = labelIds[i];
                                int userAttitude = Integer.parseInt(userAttitudes[i]);
                                // 检查 labelId 是否为 null 或空字符串
                                if (labelId == null || labelId.trim().isEmpty()) {
                                    continue; // 跳过该条目
                                }
                                // 检查 labelId 和 userAttitude 是否分别与 cascaderLabelIds 和 userAttitudeArr 的相同索引位置的值相同
                                if (Objects.equals(labelId, queryCascaderLabelId) &&
                                        userAttitude == queryUserAttitude) {
                                    return true;
                                }
                            }
                        }
                        return false;
                    })
                    .collect(Collectors.toList());
        }else{
            filteredRecords = feedbackRecordList;
        }

//        Page<FeedbackRecord> feedbackRecordPage = (Page<FeedbackRecord>) feedbackRecordList;
        //配置
        String configIds = filteredRecords.stream()
                .filter(x->StringUtils.isNotEmpty(x.getConfigIds()))
                .map(FeedbackRecord::getConfigIds)
                .collect(Collectors.joining(","));
        String userLabelIds = filteredRecords.stream()
                .filter(x -> StringUtils.isNotEmpty(x.getUserLabelIds()))
                .map(FeedbackRecord::getUserLabelIds)
                .collect(Collectors.joining(","));
        String labelIds = null;
        List<FeedbackUserLabelRecord> userLabelList = new ArrayList<>();
        if (StringUtils.isNotEmpty(userLabelIds)) {
            userLabelList = feedbackUserLabelRecordMapper.selectUserLabelByIds(userLabelIds.split(","));
            labelIds = userLabelList.stream()
                    .filter(x -> x.getLabelId() != null)
                    .map(x -> x.getLabelId().toString())
                    .collect(Collectors.joining(","));
        }
        //标签
        if (StringUtils.isNotEmpty(labelIds)) {
            configIds = configIds + "," + labelIds;
        }

        String[] typeArr = {"5", "6", "7"};
        List<FeedbackConfig> labelConfigList = feedbackConfigMapper.selectByTypes(typeArr);
        List<FeedbackConfig> configList = feedbackConfigMapper.selectByIds(configIds.split(","));
        // 二级问题标签
        String[] problemArr = {"9"};
        List<FeedbackConfig> problemConfigList = feedbackConfigMapper.selectByTypes(problemArr);

        int i = 0;
        long prevId = 0;
        long nextId = 0;
        for (FeedbackRecord feedbackRecord : filteredRecords) {
            outRecord = new FeedbackRecordResultVo();
            //上一个下一个
            if (i == 0) {
                prevId = 0;
            } else {
                prevId = filteredRecords.get(i - 1).getId();
            }

            if (i == filteredRecords.size() - 1) {
                nextId = 0;
            } else {
                nextId = filteredRecords.get(i + 1).getId();
            }
            i++;

            //相同属性赋值
            BeanUtils.copyProperties(feedbackRecord, outRecord);
            if(feedbackRecord.getFileList()!=null && !feedbackRecord.getFileList().isEmpty()){
                outRecord.setFileList( Arrays.asList(feedbackRecord.getFileList().split(",,,,")));
            }else{
                outRecord.setFileList(new ArrayList<>());
            }
            outRecord.setConsultCount(outRecord.getConsultCount() == 0 ? null : outRecord.getConsultCount());
            outRecord.setLikeCount(outRecord.getLikeCount() == 0 ? null : outRecord.getLikeCount());
            outRecord.setViewCount(outRecord.getViewCount() == 0 ? null : outRecord.getViewCount());
            List<FeedbackConfig> currentConfigList = configList.stream()
                    .filter(x ->
                            Arrays.stream(feedbackRecord.getConfigIds().split(",")).anyMatch(y -> y.equals(x.getId().toString()))
                    )
                    .sorted(Comparator.comparing(x -> (String) x.getType()))
                    .collect(Collectors.toList());

            // 找出 type 为 1 的 FeedbackConfig 对象
            List<FeedbackConfig> brandConfigs = currentConfigList.stream()
                    .filter(config -> config.getType() != null && config.getType().equals("1"))
                    .collect(Collectors.toList());
            if(!brandConfigs.isEmpty()){
                outRecord.setBrand(brandConfigs.get(0).getName());
            }

            // 找出 type 为 10 的 FeedbackConfig 对象
            List<FeedbackConfig> categoryConfigs = currentConfigList.stream()
                    .filter(config -> config.getType() != null && config.getType().equals("10"))
                    .collect(Collectors.toList());
            if(!categoryConfigs.isEmpty()){
                outRecord.setCategory(categoryConfigs.get(0).getName());
            }

            // 找出 type 为 2 的 FeedbackConfig 对象
            List<FeedbackConfig> filteredConfigs = currentConfigList.stream()
                    .filter(config -> config.getType() != null && config.getType().equals("2"))
                    .collect(Collectors.toList());
            if(!filteredConfigs.isEmpty()){
                outRecord.setProduct(filteredConfigs.get(0).getName());
            }

            // 找出 type 为 3 的 FeedbackConfig 对象
            List<FeedbackConfig> stepConfigs = currentConfigList.stream()
                    .filter(config -> config.getType() != null && config.getType().equals("3"))
                    .collect(Collectors.toList());
            if(!stepConfigs.isEmpty()){
                outRecord.setStep(stepConfigs.get(0).getName());
            }

            // 找出 type 为 4 的 FeedbackConfig 对象
            List<FeedbackConfig> resourceConfigs = currentConfigList.stream()
                    .filter(config -> config.getType() != null && config.getType().equals("4"))
                    .collect(Collectors.toList());
            if(!resourceConfigs.isEmpty()){
                outRecord.setResource(resourceConfigs.get(0).getName());
            }



            List<FeedbackUserLabelRecord> currentUserLabelList = userLabelList.stream()
                    .filter(x ->
                            Arrays.stream(feedbackRecord.getUserLabelIds().split(",")).anyMatch(y -> y.equals(x.getId().toString()))
                    )
                    .collect(Collectors.toList());
            //构造
            List<FeedbackUserLabelRecordDTO> currentUserLabelDTOList = new ArrayList<>();
            List<String> firstLevelLabel = new ArrayList<>();
            List<String> secondLevelLabel = new ArrayList<>();
            List<String> threeLevelLabel = new ArrayList<>();
            List<String> userAttitude = new ArrayList<>();
            List<String> problemeId = new ArrayList<>();
            List<String> onesId = new ArrayList<>();
            List<String> ticketStatusNameList = new ArrayList<>();
            List<Date> ticketTime = new ArrayList<>();
            // 创建一个映射关系
            Map<String, String> attitudeMap = new HashMap<>();
            attitudeMap.put("0", "未表态");
            attitudeMap.put("1", "好");
            attitudeMap.put("2", "中");
            attitudeMap.put("3", "差");

            currentUserLabelList.forEach(x -> {
                //ones工单状态获取
                String ticketStatusName = null;
                if (StringUtils.isNotEmpty(x.getTicketStatus())) {
                    OnesUtil.TaskStatuses taskStatuses = OnesUtil.getTaskStatuses(TEAM_UUID);
                    if (taskStatuses != null) {
                        Optional<OnesUtil.StatuDetail> optional = taskStatuses.getTask_statuses().stream()
                                .filter(y -> y.getUuid().equals(x.getTicketStatus()))
                                .findFirst();
                        if (optional.isPresent()) {
                            ticketStatusName = optional.get().getName();
                        }
                    }
                }
                FeedbackUserLabelRecordDTO dto = new FeedbackUserLabelRecordDTO();
                BeanUtils.copyProperties(x, dto);
                // 问题id
                FeedbackConfig problemConfig = problemConfigList.stream().
                        filter(y -> y.getId().equals(x.getProblemId()))
                        .findFirst()
                        .orElse(null);
                if (problemConfig !=null){
                    problemeId.add(problemConfig.getName());
                }
                FeedbackConfig threeLabelConfig = labelConfigList.stream().
                        filter(y -> y.getId().equals(x.getLabelId()))
                        .findFirst()
                        .orElse(null);
                if (threeLabelConfig != null) {
                    dto.setLabelId(threeLabelConfig.getId());
                    dto.setThreeLevelLabel(threeLabelConfig.getName());
                    threeLevelLabel.add(threeLabelConfig.getName());
                    //查找一二级节点
                    FeedbackConfig secondLevelLabelConfig = labelConfigList.stream()
                            .filter(y -> y.getId().equals(threeLabelConfig.getPid()))
                            .findFirst()
                            .orElse(null);
                    if (secondLevelLabelConfig != null) {
                        dto.setSecondLevelLabel(secondLevelLabelConfig.getName());
                        secondLevelLabel.add(secondLevelLabelConfig.getName());
                        FeedbackConfig firstLevelLabelConfig = labelConfigList.stream()
                                .filter(y -> y.getId().equals(secondLevelLabelConfig.getPid()))
                                .findFirst()
                                .orElse(null);
                        if (firstLevelLabelConfig != null) {
                            dto.setFirstLevelLabel(firstLevelLabelConfig.getName());
                            firstLevelLabel.add(firstLevelLabelConfig.getName());
                        }
                        dto.setTicketStatusName(ticketStatusName);
                        if(ticketStatusName!=null){
                            ticketStatusNameList.add(ticketStatusName);
                        }
                        if(x.getTicketTime()!=null){
                            ticketTime.add(x.getTicketTime());
                        }
                        onesId.add(x.getOnesId());
                        String attitudeDescription = attitudeMap.getOrDefault(x.getUserAttitude(), "未知"); // 默认值为“未知”
                        userAttitude.add(attitudeDescription);
                        currentUserLabelDTOList.add(dto);
                    }
                }
            });
            List<FeedbackLabelDTO> currentLabelList = new ArrayList<>();
            //构造
            for (FeedbackUserLabelRecordDTO dto : currentUserLabelDTOList) {
                FeedbackLabelDTO label = new FeedbackLabelDTO();
                BeanUtils.copyProperties(dto, label);
                label.setId(dto.getLabelId());
                currentLabelList.add(label);
            }
            outRecord.setFeedbackContent(feedbackRecord.getFeedbackContent())
                    .setFirstLevelLabel(firstLevelLabel)
                    .setSecondLevelLabel(secondLevelLabel)
                    .setThreeLevelLabel(threeLevelLabel)
                    .setFeedbackConfigList(currentConfigList)
                    .setTicketStatusName(ticketStatusNameList)
                    .setFeedbackType(String.valueOf(feedbackRecord.getFeedbackType()))
                    .setTicketTime(ticketTime)
                    .setOnesId(onesId)
                    .setProblemeId(problemeId)
                    .setUserAttitude(userAttitude)
                    .setUserLabels(currentUserLabelDTOList)
                    .setCascaderLabels(generateCascaderLabel(currentLabelList))
                    .setPrevId(prevId)
                    .setNextId(nextId)
                    .setReadMark(String.valueOf(feedbackRecord.getReadMark()));
            if (params.getId() != 0) {
                if (params.getId().equals(feedbackRecord.getId())) {
                    resultList.add(outRecord);
                }
            } else {
                resultList.add(outRecord);
            }
        }
        return resultList;
    }

    public List<Object> generateCascaderLabel(List<FeedbackLabelDTO> labelList) {
        List<Object> list = new ArrayList<>();
//        Map<String, List<FeedbackLabelDTO>> map1 = labelList.stream().collect(Collectors.groupingBy(FeedbackLabelDTO::getFirstLevelLabel));
//        for (Map.Entry<String, List<FeedbackLabelDTO>> entry1 : map1.entrySet()) {
//            Map<String, List<FeedbackLabelDTO>> map2 = entry1.getValue().stream().collect(Collectors.groupingBy(FeedbackLabelDTO::getSecondLevelLabel));
//            for (Map.Entry<String, List<FeedbackLabelDTO>> entry2 : map2.entrySet()) {
//                Map<String, List<FeedbackLabelDTO>> map3 = labelList.stream().collect(Collectors.groupingBy(FeedbackLabelDTO::getThreeLevelLabel));
//                for (Map.Entry<String, List<FeedbackLabelDTO>> entry3 : map3.entrySet()) {
        labelList.forEach(x -> {
            List<Object> list1 = new ArrayList<>();
            list1.add(x.getFirstLevelLabel());
            list1.add(x.getSecondLevelLabel());
            list1.add(x.getId().toString());
            list.add(list1);
        });

//                }
//            }
//        }
        return list;
    }


    @Override
    public CommonResult<FeedbackAnalysisResult> getFeedbackStatistics(FeedbackAnalysisParams params) {
        List<String> productName = new ArrayList<>();
        if(params.getProductArr()!=null &&params.getProductArr().length>0){
            for (int i = 0; i < params.getProductArr().length; i++) {
                FeedbackConfig feedbackConfig = feedbackConfigMapper.selectByPrimaryKey(Long.valueOf(params.getProductArr()[i]));
                productName.add(feedbackConfig.getName());
            }
        }
        List<FeedbackConfig> configList = feedbackConfigMapper.selectByFlag(1);
        // 将 configList 转换为 Map<Integer, String>，键是 id，值是 name
        Map<Integer, String> configMap = configList.stream()
                .collect(Collectors.toMap(FeedbackConfig::getId, FeedbackConfig::getName));
        FeedbackAnalysisResult result = new FeedbackAnalysisResult();
        PageHelper.startPage(params.getCurrent(), params.getPageSize());
        List<AnalysisDetailDTO> analysisDTOList = feedbackAnalysisDataMapper.selectFeedbackStatisticsByParams(params);
        analysisDTOList.forEach(x -> {
            x.setBrandId(x.getBrand());
            x.setBrand(configMap.get(Integer.valueOf(x.getBrand())));
            x.setCategoryId(x.getCategory());
            if(x.getCategory()!=null&&!x.getCategory().isEmpty()){
                x.setCategory(configMap.get(Integer.valueOf(x.getCategory())));
            }
            x.setProductId(x.getProduct());
            x.setProduct(configMap.get(Integer.valueOf(x.getProduct())));
            if (StringUtils.isNotEmpty(x.getStep())) {
                //顺序不能移动
                x.setStepId(x.getStep());
                x.setStep(configMap.get(Integer.valueOf(x.getStep())));
            }
            if (StringUtils.isNotEmpty(x.getSource())) {
                x.setSourceId(x.getSource());
                x.setSource(configMap.get(Integer.valueOf(x.getSource())));
            }
            if (StringUtils.isNotEmpty(x.getFirstLevelLabel())) {
                x.setFirstLevelLabelId(x.getFirstLevelLabel());
                x.setFirstLevelLabel(configMap.get(Integer.valueOf(x.getFirstLevelLabel())));
            }
            if (StringUtils.isNotEmpty(x.getSecondLevelLabel())) {
                x.setSecondLevelLabelId(x.getSecondLevelLabel());
                x.setSecondLevelLabel(configMap.get(Integer.valueOf(x.getSecondLevelLabel())));
            }
            if (StringUtils.isNotEmpty(x.getThreeLevelLabel())) {
                x.setThreeLevelLabelId(x.getThreeLevelLabel());
                x.setThreeLevelLabel(configMap.get(Integer.valueOf(x.getThreeLevelLabel())));
            }
        });
        Page<AnalysisDetailDTO> analysisPage = (Page<AnalysisDetailDTO>) analysisDTOList;
        result.setAnalysisList(analysisDTOList);
        //词云数据
        List<FeedbackAnalysisData> analysisDataList = feedbackAnalysisDataMapper.selectByParams(params);
        analysisDataList.forEach(x -> {
            x.setBrand(configMap.get(Integer.valueOf(x.getBrand())));
            if(x.getCategory()!=null&&!x.getCategory().isEmpty()){
                x.setCategory(configMap.get(Integer.valueOf(x.getCategory())));
            }
            x.setProduct(configMap.get(Integer.valueOf(x.getProduct())));
            x.setStep(configMap.get(Integer.valueOf(x.getStep())));
            x.setSource(configMap.get(Integer.valueOf(x.getSource())));
            x.setFirstLevelLabel(configMap.get(Integer.valueOf(x.getFirstLevelLabel())));
            x.setSecondLevelLabel(configMap.get(Integer.valueOf(x.getSecondLevelLabel())));
            x.setThreeLevelLabel(configMap.get(Integer.valueOf(x.getThreeLevelLabel())));
        });
        getWordCloudDataList(analysisDataList, result);
        //标签占比数据
        getLabelPercentageData(analysisDataList, result,
                params.getShowFirstLabel(),params.getShowSecondLabel(),params.getShowThreeLabel(),
                productName);
        //单标签占比趋势分析数据
        getTrendTagList(analysisDataList, result, params.getBeginTime(), params.getEndTime(),params.getShowFirstLabel(),params.getShowSecondLabel(),params.getShowThreeLabel());
        //单标签用户态度对比分析数据
        getUserAttitudeData(analysisDataList, result,params.getShowFirstLabel(),params.getShowSecondLabel(),params.getShowThreeLabel());
        // 产品用户态度对比分析数据
        getUserAttitudeProductData(analysisDataList, result);
        // 产品用户态度趋势图
        getProductTrendTagList(analysisDataList,result, params.getBeginTime(), params.getEndTime());
        // 产品用户态度
        getUserAttitudeProductData(analysisDataList,result);
        return CommonResult.Success((int) analysisPage.getTotal(), result);
    }

    public static final List<String> feedback_statistics_export_head = Arrays.asList(new String[]{
            "产品品牌", "产品品类","产品型号", "反馈阶段", "反馈来源", "一级标签", "二级标签", "三级标签", "用户态度", "标签数量", "标签占比"});
    public static final List<String> feedback_book_content_export_feild = Arrays.asList(new String[]{
            "brand", "category","product", "step", "source", "firstLevelLabel", "secondLevelLabel", "threeLevelLabel", "userAttitude", "labelCount", "labelPercentage"});

    @Override
    public CommonResult<String> exportFeedbackStatistics(FeedbackAnalysisParams params) {
        List<FeedbackConfig> configList = feedbackConfigMapper.selectByFlag(1);
        // 将 configList 转换为 Map<Integer, String>，键是 id，值是 name
        Map<Integer, String> configMap = configList.stream()
                .collect(Collectors.toMap(FeedbackConfig::getId, FeedbackConfig::getName));
        List<AnalysisDetailDTO> analysisDTOList = feedbackAnalysisDataMapper.selectFeedbackStatisticsByParams(params);
        analysisDTOList.forEach(x -> {
            x.setBrand(configMap.get(Integer.valueOf(x.getBrand())));
            x.setCategory(configMap.get(Integer.valueOf(x.getCategory())));
            x.setProduct(configMap.get(Integer.valueOf(x.getProduct())));
            if (StringUtils.isNotEmpty(x.getStep())) {
                x.setStep(configMap.get(Integer.valueOf(x.getStep())));
            }
            if (StringUtils.isNotEmpty(x.getSource())) {
                x.setSource(configMap.get(Integer.valueOf(x.getSource())));
            }
            if (StringUtils.isNotEmpty(x.getFirstLevelLabel())) {
                x.setFirstLevelLabel(configMap.get(Integer.valueOf(x.getFirstLevelLabel())));
            }
            if (StringUtils.isNotEmpty(x.getSecondLevelLabel())) {
                x.setSecondLevelLabel(configMap.get(Integer.valueOf(x.getSecondLevelLabel())));
            }
            if (StringUtils.isNotEmpty(x.getThreeLevelLabel())) {
                x.setThreeLevelLabel(configMap.get(Integer.valueOf(x.getThreeLevelLabel())));
            }
            x.setLabelPercentage(x.getLabelPercentage() + "%");
            x.setUserAttitude(StringUtils.isEmpty(x.getUserAttitude()) ? null : Dictionary.USER_ATTITUDE.fromValue(Integer.parseInt(x.getUserAttitude())).getChineseName());
        });
        //生成excel
        String excelPath = null;
        try {
            excelPath = ExcelDealUtil.exportObjectToExcel(feedback_statistics_export_head, feedback_book_content_export_feild, analysisDTOList, EXPORT_EXCEL_PATH);
        } catch (Exception e) {
            e.getMessage();
        }
        //上传至云存储
        String url = null;
        File file = new File(excelPath);
        try {
            url = openstorage.uploadFileNew(new FileInputStream(file),
                    "talkres", "feedback", file.getName());
        } catch (FileNotFoundException e) {
            log.error("upload excel file error:" + e.getMessage());
        }
        return CommonResult.Success(url);
    }

    @Override
    public CommonResult<List<OnesUtil.StatuDetail>> getTaskStatuses() {
        OnesUtil.TaskStatuses taskStatuses = OnesUtil.getTaskStatuses(TEAM_UUID);
        if (taskStatuses != null) {
            return CommonResult.Success(taskStatuses.getTask_statuses());
        } else {
            return CommonResult.Fail();
        }
    }

    @Override
    public CommonResult<Boolean> multiUpdateFeedbackStatistics() {
        List<FeedbackAnalysisData> analysisDataList = feedbackAnalysisDataMapper.selectAll();
        analysisDataList.forEach(x -> {
            dealFeedbackAnalysisData(x.getFeedbackRecordId());
        });
        return CommonResult.Success();
    }

    public void getWordCloudDataList(List<FeedbackAnalysisData> analysisDataList, FeedbackAnalysisResult result) {
        Map<String, List<FeedbackAnalysisData>> map = analysisDataList.stream()
                .sorted(Comparator.comparing(data -> {
                    Dictionary.STEP step = Dictionary.STEP.findByKey(data.getStep());
                    return step != null ? step.ordinal() : Integer.MAX_VALUE;
                }))
                .collect(Collectors.groupingBy(FeedbackAnalysisData::getStep, LinkedHashMap::new, Collectors.toList()));
        //增加个客户之声（整体）
        if (!CollectionUtils.isEmpty(analysisDataList)) {
            FeedbackAnalysisResult.WordCloudData wordCloudDataForAll = new FeedbackAnalysisResult.WordCloudData()
                    .setCloudId("客户之声")
                    .setCloudName("客户之声")
                    .setSlogan("用户对产品的整体关注点")
                    .setDetailList(countThreeLabel(analysisDataList));
            result.getWordCloudDataList().add(wordCloudDataForAll);
        }
        //阶段
        for (Map.Entry<String, List<FeedbackAnalysisData>> entry : map.entrySet()) {
            FeedbackAnalysisResult.WordCloudData wordCloudData = new FeedbackAnalysisResult.WordCloudData();
            Dictionary.STEP step = Dictionary.STEP.findByKey(entry.getKey());
            if (step != null) {
                wordCloudData.setCloudName(step.cloudName());
                wordCloudData.setSlogan(step.slogan());
            }
            wordCloudData.setCloudId(entry.getKey());
            //统计三级标签的数量
            List<FeedbackAnalysisResult.CloudDetail> detailList = countThreeLabel(entry.getValue());
            wordCloudData.setDetailList(detailList);
            result.getWordCloudDataList().add(wordCloudData);
        }
        // 创建新的列表来存储排序后的结果
        List<FeedbackAnalysisResult.WordCloudData> sortedList = new ArrayList<>();
        // 标记是否已添加"使用阶段-使用后反馈"的元素
        boolean addedFeedbackPhase = false;

        for (FeedbackAnalysisResult.WordCloudData data : result.getWordCloudDataList()) {
            // 如果当前元素是"咨询阶段-购买前咨询"，且还没有添加"使用阶段-使用后反馈"
            if (data.getCloudName().equals("咨询阶段-购买前咨询")) {
                sortedList.add(data);
            } else if (data.getCloudName().equals("使用阶段-使用后反馈")) {
                // 添加"使用阶段-使用后反馈"的元素，并标记
                sortedList.add(data);
                addedFeedbackPhase = true;
            } else {
                // 对于其他元素，直接添加到结果列表中
                sortedList.add(data);
            }
        }
        // 将"咨询阶段-购买前咨询"的元素放在"使用阶段-使用后反馈"之前
        List<FeedbackAnalysisResult.WordCloudData> finalList = new ArrayList<>();

        for (FeedbackAnalysisResult.WordCloudData data : sortedList) {
            if (data.getCloudName().equals("使用阶段-使用后反馈") && addedFeedbackPhase) {
                // 在添加到最终列表之前，先添加所有"咨询阶段-购买前咨询"
                for (FeedbackAnalysisResult.WordCloudData temp : sortedList) {
                    if (temp.getCloudName().equals("咨询阶段-购买前咨询")) {
                        finalList.add(temp);
                    }
                }
                addedFeedbackPhase = false;  // 确保只添加一次
            }
            finalList.add(data);
        }

        int count = 0;
        for (int i = 0; i < finalList.size(); i++) {
            FeedbackAnalysisResult.WordCloudData item = finalList.get(i);
            if (item.getCloudName().equals("咨询阶段-购买前咨询")) {
                count++;
                // 当找到第二个时，删除它
                if (count == 2) {
                    finalList.remove(i);
                    break; // 找到并删除后退出循环
                }
            }
        }
        result.setWordCloudDataList(finalList);
    }

    public List<FeedbackAnalysisResult.CloudDetail> countThreeLabel(List<FeedbackAnalysisData> list) {
        Map<String, Long> threeLevelLabelCount = list.stream()
                .filter(x -> StringUtils.isNotEmpty(x.getThreeLevelLabel()))
                .collect(Collectors.groupingBy(
                        FeedbackAnalysisData::getThreeLevelLabel,
                        LinkedHashMap::new,
                        Collectors.summingLong(x -> x.getConsultCount() != null && x.getConsultCount() != 0 ? x.getConsultCount() : 1)
                ));

        List<FeedbackAnalysisResult.CloudDetail> detailList = new ArrayList<>();
        for (Map.Entry<String, Long> labelEntry : threeLevelLabelCount.entrySet()) {
            FeedbackAnalysisResult.CloudDetail cloudDetail = new FeedbackAnalysisResult.CloudDetail();
            cloudDetail.setName(labelEntry.getKey());
            cloudDetail.setValue(labelEntry.getValue().intValue());
            detailList.add(cloudDetail);
        }
        return detailList;
    }


    public void getLabelPercentageData(List<FeedbackAnalysisData> analysisDataList, FeedbackAnalysisResult result,
                                       Boolean showFirstLabel,Boolean showSecondLabel,Boolean showThreeLabel,
                                       List<String> productArr
                                       ) {

        // 根据布尔值确定分组的标签层级（优先级：三级 > 二级 > 一级）
        Function<FeedbackAnalysisData, String> labelClassifier;
        Predicate<FeedbackAnalysisData> labelFilter;

        if (showThreeLabel) {
            labelClassifier = FeedbackAnalysisData::getThreeLevelLabel;
            labelFilter = x -> StringUtils.isNotEmpty(x.getThreeLevelLabel());
        } else if (showSecondLabel) {
            labelClassifier = FeedbackAnalysisData::getSecondLevelLabel;
            labelFilter = x -> StringUtils.isNotEmpty(x.getSecondLevelLabel());
        } else if (showFirstLabel) {
            labelClassifier = FeedbackAnalysisData::getFirstLevelLabel;
            labelFilter = x -> StringUtils.isNotEmpty(x.getFirstLevelLabel());
        } else {
            // 默认回退到三级标签（如果所有开关都为 false）
            labelClassifier = FeedbackAnalysisData::getThreeLevelLabel;
            labelFilter = x -> StringUtils.isNotEmpty(x.getThreeLevelLabel());
        }

        if (CollectionUtils.isEmpty(analysisDataList)) {
            result.setLabelPercentageData(null);
        } else {
            FeedbackAnalysisResult.LabelPercentageData labelPercentageData = new FeedbackAnalysisResult.LabelPercentageData();
            FeedbackAnalysisResult.BarDataDetail barDataDetail = new FeedbackAnalysisResult.BarDataDetail();

            // 根据品牌分组
            Map<String, List<FeedbackAnalysisData>> productGroupMap = analysisDataList.stream()
                    .collect(Collectors.groupingBy(FeedbackAnalysisData::getProduct,LinkedHashMap::new,Collectors.toList()));
            // 按照前端传入数组排序后的legend列表
            List<String> legendList = new ArrayList<>();
            if (!productArr.isEmpty()) {
                // 按productArr顺序过滤存在的品牌
                legendList = productArr.stream()
                        .filter(productGroupMap::containsKey)
                        .collect(Collectors.toList());
            } else {
                legendList = new ArrayList<>(productGroupMap.keySet());
            }

            // 生成 legend 列表（型号）
//            List<String> legendList = new ArrayList<>(productGroupMap.keySet());
            // 生成 labels 列表（三级标签）
            List<String> labelList = analysisDataList.stream()
                    .map(labelClassifier)
                    .filter(StringUtils::isNotEmpty)
//                    .map(FeedbackAnalysisData::getThreeLevelLabel)
                    .distinct()
                    .collect(Collectors.toList());
            barDataDetail.setLegend(legendList);
            barDataDetail.setLabels(labelList);
            // 初始化 series 列表
            List<FeedbackAnalysisResult.Series> seriesList = new ArrayList<>();
            //对每个品牌进行处理 前端产品数组一一对应逻辑
            for (String product : legendList) {
                List<FeedbackAnalysisData> productData = productGroupMap.get(product);
                Map<String, Long> labelCountMap = productData.stream()
                        .filter(labelFilter)
                        .collect(Collectors.groupingBy(
                                labelClassifier,
                                LinkedHashMap::new,
                                Collectors.summingLong(x -> (x.getConsultCount() != null && x.getConsultCount() != 0) ? x.getConsultCount() : 1)
                        ));

                long total = labelCountMap.values().stream().mapToLong(Long::longValue).sum();
                FeedbackAnalysisResult.Series series = new FeedbackAnalysisResult.Series();
                series.setName(product);

                List<Double> percentages = new ArrayList<>();
                List<Long> counts = new ArrayList<>();
                for (String label : labelList) {
                    long count = labelCountMap.getOrDefault(label, 0L);
                    percentages.add(total == 0 ? 0.0 : Math.round((count * 10000.0 / total)) / 10000.0);
                    counts.add(count);
                }
                series.setData(percentages);
                series.setLabelCountData(counts);
                seriesList.add(series);
            }
            // 对每个品牌进行处理 没有前端产品数组一一对应逻辑
//            for (Map.Entry<String, List<FeedbackAnalysisData>> entry : productGroupMap.entrySet()) {
//                String product = entry.getKey();
//                List<FeedbackAnalysisData> productDataList = entry.getValue();
//                // 统计该品牌下每个标签的数量
//                Map<String, Long> labelCountMap = productDataList.stream()
//                        .filter(labelFilter) // 使用动态标签过滤器
////                        .filter(x -> StringUtils.isNotEmpty(x.getThreeLevelLabel()))
//                        .collect(Collectors.groupingBy(
//                                labelClassifier, // 使用动态标签分类器
////                                FeedbackAnalysisData::getThreeLevelLabel,
//                                LinkedHashMap::new,
//                                Collectors.summingLong(x -> x.getConsultCount() != null && x.getConsultCount() != 0 ? x.getConsultCount() : 1)
//                        ));
//
//                // 计算该品牌下的所有标签的总数量
//                long totalLabels = labelCountMap.values().stream().mapToInt(Long::intValue).sum();//productDataList.size();
//                // 构建 series 数据项
//                FeedbackAnalysisResult.Series series = new FeedbackAnalysisResult.Series();
//                series.setName(product);
//                // 计算每个标签的占比并加入 series.data 列表
//                List<Double> labelPercentageList = new ArrayList<>();
//                List<Long> labelCountList = new ArrayList<>();
//                for (String label : labelList) {
//                    long count = labelCountMap.getOrDefault(label, 0L);
//                    double percentage = totalLabels == 0 ? 0.0 : (double) count / totalLabels;
//                    // 四舍五入并保留两位小数
//                    percentage = Math.round(percentage * 10000.0) / 10000.0;
//                    labelPercentageList.add(percentage);
//                    labelCountList.add(count);
//                }
//                series.setData(labelPercentageList);
//                series.setLabelCountData(labelCountList);
//                seriesList.add(series);
//            }
            barDataDetail.setSeries(seriesList);
            labelPercentageData.setFullBarData(barDataDetail);

            // 处理态度数据
            Map<Integer, String> attitudeMap = new HashMap<>();
            attitudeMap.put(1, "好");
            attitudeMap.put(2, "中");
            attitudeMap.put(3, "差");
            attitudeMap.put(0, "未表态");

            Map<String, FeedbackAnalysisResult.BarDataDetail> attitudeBarData = new HashMap<>();
            // 没有对前端数组作一一匹配
//            for (Map.Entry<Integer, String> entry : attitudeMap.entrySet()) {
            // 有对前端数组作一一匹配
            attitudeMap.forEach((attitudeCode, attitudeName) -> {
//                Integer attitude = entry.getKey();
//                String attitudeLabel = entry.getValue();
                // 获取该态度下的数据
                List<FeedbackAnalysisData> filteredData = analysisDataList.stream()
                        .filter(data -> data.getUserAttitude() != null && data.getUserAttitude().equals(attitudeCode))
                        .collect(Collectors.toList());
                // 再次根据品牌分组
                Map<String, List<FeedbackAnalysisData>> filteredProductGroupMap = filteredData.stream()
                        .collect(Collectors.groupingBy(FeedbackAnalysisData::getProduct,LinkedHashMap::new,Collectors.toList()));
                // 创建新的 BarDataDetail 对象
                FeedbackAnalysisResult.BarDataDetail attitudeBarDataDetail = new FeedbackAnalysisResult.BarDataDetail();
                // 生成排序后的attitudeLegendList
                List<String> attitudeLegendList;
                if (!productArr.isEmpty()) {
                    attitudeLegendList = productArr.stream()
                            .filter(filteredProductGroupMap::containsKey)
                            .collect(Collectors.toList());
                } else {
                    attitudeLegendList = new ArrayList<>(filteredProductGroupMap.keySet());
                }
                // 生成新的 legend 列表（该态度下的品牌）
//                List<String> attitudeLegendList = new ArrayList<>(filteredProductGroupMap.keySet());
                // 生成新的 labels 列表（该态度下的标签）
                List<String> attitudeLabelList = filteredData.stream()
                        .map(labelClassifier) // 使用相同的标签分类器
                        .filter(StringUtils::isNotEmpty)
//                        .map(FeedbackAnalysisData::getThreeLevelLabel)
                        .distinct()
                        .collect(Collectors.toList());
                attitudeBarDataDetail.setLegend(attitudeLegendList);
                attitudeBarDataDetail.setLabels(attitudeLabelList);
                // 初始化 series 列表
                List<FeedbackAnalysisResult.Series> attitudeSeriesList = new ArrayList<>();
                // 处理每个品牌
                for (Map.Entry<String, List<FeedbackAnalysisData>> productEntry : filteredProductGroupMap.entrySet()) {
                    String product = productEntry.getKey();
                    List<FeedbackAnalysisData> productAttitudeDataList = productEntry.getValue();
                    // 统计该品牌下每个标签的数量
                    Map<String, Long> productLabelCountMap = productAttitudeDataList.stream()
                            .filter(labelFilter)
//                            .filter(x -> StringUtils.isNotEmpty(x.getThreeLevelLabel()))
                            .collect(Collectors.groupingBy(
                                    labelClassifier,
//                                    FeedbackAnalysisData::getThreeLevelLabel,
                                    LinkedHashMap::new,
                                    Collectors.summingLong(x -> x.getConsultCount() != null && x.getConsultCount() != 0 ? x.getConsultCount() : 1)
                            ));
                    // 计算该品牌下的标签总数量
                    long totalProductLabels = productLabelCountMap.values().stream().mapToInt(Long::intValue).sum();//productAttitudeDataList.size();
                    // 创建 series 数据项
                    FeedbackAnalysisResult.Series attitudeSeries = new FeedbackAnalysisResult.Series();
                    attitudeSeries.setName(product);
                    // 计算该品牌下每个标签的占比
                    List<Double> attitudeLabelPercentageList = new ArrayList<>();
                    List<Long> attitudeLabelCountList = new ArrayList<>();
                    for (String label : attitudeLabelList) {
                        long count = productLabelCountMap.getOrDefault(label, 0L);
                        double percentage = totalProductLabels == 0 ? 0.0 : (double) count / totalProductLabels;
                        attitudeLabelPercentageList.add(percentage);
                        attitudeLabelCountList.add(count);
                    }
                    attitudeSeries.setData(attitudeLabelPercentageList);
                    attitudeSeries.setLabelCountData(attitudeLabelCountList);
                    attitudeSeriesList.add(attitudeSeries);
                }
                attitudeBarDataDetail.setSeries(attitudeSeriesList);
                attitudeBarData.put(attitudeName, attitudeBarDataDetail);
            });
            // 将fullbarData数据转为全部
            attitudeBarData.put("全部",barDataDetail);
            labelPercentageData.setAttitudeBarData(attitudeBarData);
            result.setLabelPercentageData(labelPercentageData);
        }
    }

    public void getProductTrendTagList(List<FeedbackAnalysisData> analysisDataList, FeedbackAnalysisResult result, String beginTime, String endTime){
        // 创建一个态度到产品数据的映射
        Map<Integer, List<FeedbackAnalysisData>> labelToProductMap = analysisDataList.stream()
                .filter(x -> StringUtils.isNotEmpty(String.valueOf(x.getUserAttitude())))
                .collect(Collectors.groupingBy(FeedbackAnalysisData::getUserAttitude,LinkedHashMap::new,Collectors.toList()));
        // 创建态度 ID 到描述的映射
        Map<Integer, String> attitudeMapping = new HashMap<>();
        attitudeMapping.put(0, "未表态");
        attitudeMapping.put(1, "好");
        attitudeMapping.put(2, "中");
        attitudeMapping.put(3, "差");
        // 获取当前日期和六个月前的日期，若 beginTime 或 endTime 不为空，则使用这些时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDate endDate = (StringUtils.isNotEmpty(endTime))
                ? LocalDateTime.parse(endTime, formatter).toLocalDate()
                : LocalDate.now();

        LocalDate startDate = (StringUtils.isNotEmpty(beginTime))
                ? LocalDateTime.parse(beginTime, formatter).toLocalDate()
                : endDate.minusMonths(6);

        // 3. 过滤有效数据（时间范围内且 userAttitude 非空）
        List<FeedbackAnalysisData> filteredData = analysisDataList.stream()
                .filter(data -> data.getFeedbackTime() != null
                        && !data.getFeedbackTime().isBefore(startDate)
                        && !data.getFeedbackTime().isAfter(endDate)
                        && data.getUserAttitude() != null)
                .collect(Collectors.toList());

        // 按日期分组，再按产品分组，最后按态度分组统计数量
//        Map<LocalDate, Map<String, Map<Integer, Long>>> groupedData = filteredData.stream()
//                .filter(x -> StringUtils.isNotEmpty(String.valueOf(x.getUserAttitude())))
//                .collect(Collectors.groupingBy(
//                        FeedbackAnalysisData::getFeedbackTime,
//                        TreeMap::new, // 保证日期排序
//                        Collectors.groupingBy(
//                                FeedbackAnalysisData::getProduct,
//                                Collectors.groupingBy(
//                                        FeedbackAnalysisData::getUserAttitude,
//                                        Collectors.counting()
//                                )
//                        )
//                ));
        // 按日期分组，再按产品分组，最后按态度分组统计 consultCount（处理无效值）
        Map<LocalDate, Map<String, Map<Integer, Long>>> groupedData = filteredData.stream()
                .filter(x -> StringUtils.isNotEmpty(String.valueOf(x.getUserAttitude())))
                .collect(Collectors.groupingBy(
                        FeedbackAnalysisData::getFeedbackTime,
                        TreeMap::new,
                        Collectors.groupingBy(
                                FeedbackAnalysisData::getProduct,
                                Collectors.groupingBy(
                                        FeedbackAnalysisData::getUserAttitude,
                                        // 关键修改：累加 consultCount，无效值替换为 1
                                        Collectors.summingLong(data ->
                                                (data.getConsultCount() != null && data.getConsultCount() != 0)
                                                        ? data.getConsultCount()
                                                        : 1
                                        )
                                )
                        )
                ));


        // 2. 生成连续的日期列表（包含 startDate 到 endDate 的所有日期）
        List<LocalDate> allDates = new ArrayList<>();
        LocalDate currentDate = startDate;
        while (!currentDate.isAfter(endDate)) {
            allDates.add(currentDate);
            currentDate = currentDate.plusDays(1);
        }
        List<String> dateStrings = allDates.stream()
                .map(LocalDate::toString)
                .collect(Collectors.toList());

        // 收集所有产品和态度类型
        Set<String> products = filteredData.stream()
                .map(FeedbackAnalysisData::getProduct)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        List<String> sortedProducts = new ArrayList<>(products);
        Collections.sort(sortedProducts);

        Set<Integer> attitudes = filteredData.stream()
                .map(FeedbackAnalysisData::getUserAttitude)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        List<Integer> sortedAttitudes = new ArrayList<>(attitudes);
        Collections.sort(sortedAttitudes);

        // 计算每个产品在每个日期的总数量
//        Map<LocalDate, Map<String, Long>> productDateTotal = new HashMap<>();
//        for (LocalDate date : allDates) {
//            Map<String, Map<Integer, Long>> productMap = groupedData.getOrDefault(date, Collections.emptyMap());
//            Map<String, Long> totals = new HashMap<>();
//            // 遍历所有产品（包括可能未出现在数据中的产品）
//            for (String product : productMap.keySet()) {
//                Map<Integer, Long> attitudeCounts = productMap.getOrDefault(product, Collections.emptyMap());
//                long total = attitudeCounts.values().stream().mapToLong(Long::longValue).sum();
//                totals.put(product, total);
//            }
//            productDateTotal.put(date, totals);
//        }

        // 1. 预先计算每个产品在整个时间段内的总记录数（所有日期、所有态度）
        Map<String, Long> productTotalMap = new HashMap<>();
        groupedData.values().forEach(productMap ->
                productMap.forEach((product, attitudeMap) -> {
                    long total = attitudeMap.values().stream().mapToLong(Long::longValue).sum();
                    productTotalMap.put(product, productTotalMap.getOrDefault(product, 0L) + total);
                })
        );


        // 构建AttitudeDateTag 产品改为当前日期当前态度/当前日期总态度
        FeedbackAnalysisResult.AttitudeDateTag attitudeDateTag = new FeedbackAnalysisResult.AttitudeDateTag();
        attitudeDateTag.setDate(dateStrings);

        List<FeedbackAnalysisResult.AttitudeTag> attitudeTags = new ArrayList<>();
        for (Integer attitude : sortedAttitudes) {
            FeedbackAnalysisResult.AttitudeTag attitudeTag = new FeedbackAnalysisResult.AttitudeTag();
            String attitudeDescription = attitudeMapping.getOrDefault(attitude, "未知");
            attitudeTag.setAttitude(String.valueOf(attitudeDescription));
            List<FeedbackAnalysisResult.ProductTrend> productTrends = new ArrayList<>();

            for (String product : sortedProducts) {
                FeedbackAnalysisResult.ProductTrend productTrend = new FeedbackAnalysisResult.ProductTrend();
                productTrend.setProduct(product);
                List<Double> percentages = new ArrayList<>();
                List<Long> labelCounts = new ArrayList<>();

                // 修改后的每日独立计算逻辑
                for (LocalDate date : allDates) {
                    // 获取当天该产品的数据
                    Map<String, Map<Integer, Long>> dailyProductMap = groupedData.getOrDefault(date, Collections.emptyMap());

                    // 当前产品当天的态度数量（非累计）
                    Long count = dailyProductMap.getOrDefault(product, Collections.emptyMap())
                            .getOrDefault(attitude, 0L);

                    // 当前产品当天所有态度的总数（非累计）
                    Long total = dailyProductMap.getOrDefault(product, Collections.emptyMap())
                            .values().stream()
                            .mapToLong(Long::longValue)
                            .sum();

                    double percentage = (total == 0) ? 0.0 : (count.doubleValue() / total) * 100;
                    percentage = Math.round(percentage * 100.0) / 100.0;

                    percentages.add(percentage);
                    labelCounts.add(count);
                }

                productTrend.setPercentage(percentages);
                productTrend.setLabelCount(labelCounts);
                productTrends.add(productTrend);
            }

            attitudeTag.setProductTrends(productTrends);
            attitudeTags.add(attitudeTag);
        }

        attitudeDateTag.setAttitudeTags(attitudeTags);
        result.setAttitudeDateTag(attitudeDateTag);


//        // 构建AttitudeDateTag 累计到当前日期的 count/累计到当前日期的总数量（所有态度）
//        FeedbackAnalysisResult.AttitudeDateTag attitudeDateTag = new FeedbackAnalysisResult.AttitudeDateTag();
//        attitudeDateTag.setDate(dateStrings);
//
//        List< FeedbackAnalysisResult.AttitudeTag> attitudeTags = new ArrayList<>();
//        for (Integer attitude : sortedAttitudes) {
//            FeedbackAnalysisResult.AttitudeTag attitudeTag = new  FeedbackAnalysisResult.AttitudeTag();
//            // 使用映射获取对应的态度描述
//            String attitudeDescription = attitudeMapping.getOrDefault(attitude, "未知");
//            attitudeTag.setAttitude(String.valueOf(attitudeDescription));
//            List< FeedbackAnalysisResult.ProductTrend> productTrends = new ArrayList<>();
//
//            for (String product : sortedProducts) {
//                FeedbackAnalysisResult.ProductTrend productTrend = new  FeedbackAnalysisResult.ProductTrend();
//                productTrend.setProduct(product);
//                List<Double> percentages = new ArrayList<>();
//                List<Long> labelCounts = new ArrayList<>();
//
//
//                // 1. 预计算每个日期、每个产品、每个态度的累计总数
//                Map<LocalDate, Map<String, Map<Integer, Long>>> cumulativeData = new TreeMap<>();
//                Map<String, Map<Integer, Long>> runningTotals = new HashMap<>();
//
//                for (LocalDate date : allDates) {
//                    // 深拷贝之前的累计数据
//                    Map<String, Map<Integer, Long>> currentCopy = new HashMap<>();
//                    runningTotals.forEach((product1, attMap) ->
//                            currentCopy.put(product1, new HashMap<>(attMap))
//                    );
//
//                    // 获取当天的数据
//                    Map<String, Map<Integer, Long>> dailyData =
//                            groupedData.getOrDefault(date, Collections.emptyMap());
//
//                    // 合并当天数据到累计数据
//                    dailyData.forEach((product1, attMap) -> {
//                        Map<Integer, Long> productMap =
//                                currentCopy.computeIfAbsent(product1, k -> new HashMap<>());
//                        attMap.forEach((attitude1, count) ->
//                                productMap.merge(attitude1, count, Long::sum)
//                        );
//                    });
//
//                    // 保存到累计数据集
//                    cumulativeData.put(date, currentCopy);
//                    runningTotals = currentCopy;
//                }
//
//                // 2. 修改后的 count 和 total 计算逻辑
//                for (LocalDate date : allDates) {
//                    // 累计到当前日期的 count
//                    Long count = cumulativeData.get(date)
//                            .getOrDefault(product, Collections.emptyMap())
//                            .getOrDefault(attitude, 0L);
//
//                    // 累计到当前日期的总数量（所有态度）
//                    Long total = cumulativeData.get(date)
//                            .getOrDefault(product, Collections.emptyMap())
//                            .values().stream()
//                            .mapToLong(Long::longValue)
//                            .sum();
//
//                    // 计算百分比
//                    double percentage = (total == 0) ? 0.0 : (count.doubleValue() / total) * 100;
//                    percentage = Math.round(percentage * 100.0) / 100.0;
//
//                    percentages.add(percentage);
//                    labelCounts.add(count);
//                }
//
////                for (LocalDate date : allDates) {
////                    // 获取当前日期、产品、态度的数量
////                    Long count = groupedData.getOrDefault(date, Collections.emptyMap())
////                            .getOrDefault(product, Collections.emptyMap())
////                            .getOrDefault(attitude, 0L);
////
////                    // 修改点：使用整个时间段内该产品的总数量
////                    Long total = productTotalMap.getOrDefault(product, 0L); // 关键变化
////
////                    double percentage = (total == 0) ? 0.0 : (count.doubleValue() / total) * 100;
////                    percentage = Math.round(percentage * 100.0) / 100.0; // 保留两位小数
////
////                    percentages.add(percentage);
////                    labelCounts.add(count);
////                }
//
//                productTrend.setPercentage(percentages);
//                productTrend.setLabelCount(labelCounts);
//                productTrends.add(productTrend);
//            }
//
//            attitudeTag.setProductTrends(productTrends);
//            attitudeTags.add(attitudeTag);
//        }
//
//        attitudeDateTag.setAttitudeTags(attitudeTags);
//        result.setAttitudeDateTag(attitudeDateTag);

    }

    public void getTrendTagList(List<FeedbackAnalysisData> analysisDataList, FeedbackAnalysisResult result, String beginTime, String endTime,
                                Boolean showFirstLabel,Boolean showSecondLabel,Boolean showThreeLabel
    ) {
        // 根据布尔值确定分组的标签层级（优先级：三级 > 二级 > 一级）
        Function<FeedbackAnalysisData, String> labelClassifier;
        Predicate<FeedbackAnalysisData> labelFilter;

        if (showThreeLabel) {
            labelClassifier = FeedbackAnalysisData::getThreeLevelLabel;
            labelFilter = x -> StringUtils.isNotEmpty(x.getThreeLevelLabel());
        } else if (showSecondLabel) {
            labelClassifier = FeedbackAnalysisData::getSecondLevelLabel;
            labelFilter = x -> StringUtils.isNotEmpty(x.getSecondLevelLabel());
        } else if (showFirstLabel) {
            labelClassifier = FeedbackAnalysisData::getFirstLevelLabel;
            labelFilter = x -> StringUtils.isNotEmpty(x.getFirstLevelLabel());
        } else {
            // 默认回退到三级标签（如果所有开关都为 false）
            labelClassifier = FeedbackAnalysisData::getThreeLevelLabel;
            labelFilter = x -> StringUtils.isNotEmpty(x.getThreeLevelLabel());
        }

        // 创建一个标签到产品数据的映射
        Map<String, List<FeedbackAnalysisData>> labelToProductMap = analysisDataList.stream()
                .filter(labelFilter)
                .collect(Collectors.groupingBy(labelClassifier,LinkedHashMap::new,Collectors.toList()));


        // 创建一个标签到产品数据的映射
//        Map<String, List<FeedbackAnalysisData>> labelToProductMap = analysisDataList.stream()
//                .filter(x -> StringUtils.isNotEmpty(x.getThreeLevelLabel()))
//                .collect(Collectors.groupingBy(FeedbackAnalysisData::getThreeLevelLabel,LinkedHashMap::new,Collectors.toList()));

        List<FeedbackAnalysisResult.Tag> trendTagList = new ArrayList<>();

        // 获取当前日期和六个月前的日期，若 beginTime 或 endTime 不为空，则使用这些时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDate endDate = (StringUtils.isNotEmpty(endTime))
                ? LocalDateTime.parse(endTime, formatter).toLocalDate()
                : LocalDate.now();

        LocalDate startDate = (StringUtils.isNotEmpty(beginTime))
                ? LocalDateTime.parse(beginTime, formatter).toLocalDate()
                : endDate.minusMonths(6);

        // 遍历每个三级标签
        labelToProductMap.forEach((currentLabel, productDataList) -> {
            FeedbackAnalysisResult.Tag tag = new FeedbackAnalysisResult.Tag();
            tag.setLabel(currentLabel);
            // 获取当前标签下的所有产品
            Map<String, List<FeedbackAnalysisData>> productToDataMap = productDataList.stream()
                    .collect(Collectors.groupingBy(FeedbackAnalysisData::getProduct,LinkedHashMap::new,Collectors.toList()));
            List<FeedbackAnalysisResult.Product> productList = new ArrayList<>();
            // 遍历产品数据，按用户态度生成Product对象
            productToDataMap.forEach((productLabel, feedbackList) -> {
                // 按用户态度进行分组
                Map<String, List<FeedbackAnalysisData>> attitudeToFeedbackMap = feedbackList.stream()
                        .collect(Collectors.groupingBy(x -> x.getUserAttitude().toString(),LinkedHashMap::new,Collectors.toList()));
                // 遍历每种用户态度
                attitudeToFeedbackMap.forEach((userAttitude, userAttitudeFeedbackList) -> {
                    FeedbackAnalysisResult.Product product = new FeedbackAnalysisResult.Product();
                    product.setLabel(productLabel);
                    product.setAttitude(getAttitudeLabel(Integer.valueOf(userAttitude))); // 设置用户态度

                    // 根据日期生成趋势，仅保留六个月内的日期
                    Map<LocalDate, Long> dateCountMap = userAttitudeFeedbackList.stream()
                            // 2.24更新
                            .filter(data ->
                                    labelClassifier.apply(data).equals(currentLabel) && // 匹配当前标签层级
                                            data.getProduct().equals(productLabel) &&
                                            Objects.equals(data.getUserAttitude(), Integer.valueOf(userAttitude))
                            )
                            .filter(data -> !data.getFeedbackTime().isBefore(startDate))
                            .collect(Collectors.groupingBy(
                                    FeedbackAnalysisData::getFeedbackTime,
                                    LinkedHashMap::new,
                                    Collectors.summingLong(data -> data.getConsultCount() != null && data.getConsultCount() != 0 ? data.getConsultCount() : 1)
                            ));

                    // 计算总数量
                    long totalCount = analysisDataList.stream()
                            // 2.24更新
                            .filter(data-> labelClassifier.apply(data).equals(currentLabel) &&
                                    data.getProduct().equals(productLabel))
                            .mapToLong(data -> data.getConsultCount() != null && data.getConsultCount() != 0 ? data.getConsultCount() : 1)
                            .sum();

                    // 累计反馈数量
                    final long[] cumulativeCount = {0};
                    // 遍历近半年的每一天，生成趋势列表
                    List<FeedbackAnalysisResult.Trend> trendList = Stream.iterate(startDate, date -> date.plusDays(1))
                            .limit(java.time.temporal.ChronoUnit.DAYS.between(startDate, endDate) + 1)
                            .map(date -> {
                                FeedbackAnalysisResult.Trend trend = new FeedbackAnalysisResult.Trend();
                                trend.setDate(date.toString());

                                // 获取当天的反馈数量，如果没有数据则为 0
                                long dailyCount = dateCountMap.getOrDefault(date, 0L);
                                cumulativeCount[0] += dailyCount;

                                // 计算占比，保留两位小数
                                double percentage = new BigDecimal((double) cumulativeCount[0] / totalCount)
                                        .setScale(4, BigDecimal.ROUND_HALF_UP)
                                        .doubleValue();

                                trend.setPercentage(percentage);
                                trend.setLabelCount(cumulativeCount[0]);
                                return trend;
                            })
                            .collect(Collectors.toList());

                    product.setTrend(trendList);
                    Long allCount =trendList.get(trendList.size()-1).getLabelCount();
                    product.setAllCount(allCount);
                    productList.add(product);
                });
            });
            // 将labelCoont从大到小排序
//            List<FeedbackAnalysisResult.Product> sortedList = productList.stream()
//                    .sorted((o1, o2) -> {
//                        Long count1 = o1.getAllCount();
//                        Long count2 = o2.getAllCount();
//
//                        if (count1 == null && count2 == null) return 0;
//                        if (count1 == null) return 1;
//                        if (count2 == null) return -1;
//
//                        return count2.compareTo(count1);
//                    })
//                    .collect(Collectors.toList());

            tag.setProductData(productList);
            // 获取tag级别allcount总数
            long totalAllCount = productList.stream()
                    .map(FeedbackAnalysisResult.Product::getAllCount) // 提取 allCount 属性
                    .filter(Objects::nonNull)  // 避免空值
                    .mapToLong(Long::longValue) // 转换为 long 类型
                    .sum(); // 求和
            tag.setAllCount(totalAllCount);
            trendTagList.add(tag);
        });

        // 将tag allcount属性从大到小排序
        List<FeedbackAnalysisResult.Tag> sortedTagList = trendTagList.stream()
                .sorted((o1, o2) -> {
                    Long count1 = o1.getAllCount();
                    Long count2 = o2.getAllCount();

                    if (count1 == null && count2 == null) return 0;
                    if (count1 == null) return 1;
                    if (count2 == null) return -1;

                    return count2.compareTo(count1);
                })
                .collect(Collectors.toList());

        // 设置结果中的趋势标签列表
        result.setTrendTagList(trendTagList);
    }

    public void getUserAttitudeProductData(List<FeedbackAnalysisData> analysisDataList,FeedbackAnalysisResult result){
        // 创建态度 ID 到描述的映射
        Map<Integer, String> attitudeMapping = new HashMap<>();
        attitudeMapping.put(0, "未表态");
        attitudeMapping.put(1, "好");
        attitudeMapping.put(2, "中");
        attitudeMapping.put(3, "差");
        List< FeedbackAnalysisResult.productAttitude> productAttitudes = new ArrayList<>();
        Map<Integer, Map<String, Long>> attitudeProductCountMap = analysisDataList.stream()
                .filter(x -> StringUtils.isNotEmpty(x.getThreeLevelLabel()))
                .collect(Collectors.groupingBy(
                        FeedbackAnalysisData::getUserAttitude, // 外层按用户态度分组
                        LinkedHashMap::new, // 保持顺序
                        Collectors.groupingBy(
                                FeedbackAnalysisData::getProduct, // 内层按产品分组
                                LinkedHashMap::new,
                                Collectors.summingLong(data ->
                                        data.getConsultCount() != null && data.getConsultCount() != 0
                                                ? data.getConsultCount()
                                                : 1
                                )
                        )
                ));
        DecimalFormat decimalFormat = new DecimalFormat("#.00"); // 创建 DecimalFormat 实例
        for (Map.Entry<Integer, Map<String, Long>> attitudeEntry : attitudeProductCountMap.entrySet()) {
            Integer attitudeId = attitudeEntry.getKey();
            Map<String, Long> productCountMap = attitudeEntry.getValue();
            // 创建一个新的 ProductAttitude 对象
            FeedbackAnalysisResult.productAttitude productAttitude = new FeedbackAnalysisResult.productAttitude();
            // 使用映射获取对应的态度描述
            String attitudeDescription = attitudeMapping.getOrDefault(attitudeId, "未知");
            productAttitude.setAttitude(attitudeDescription); // 设置态度描述

            // 遍历产品计数映射并填充 AttitudeData 列表
            for (Map.Entry<String, Long> productEntry : productCountMap.entrySet()) {
                String product = productEntry.getKey();
                Long countForCurrentAttitude = productEntry.getValue();

                // 计算当前产品所有用户态度类型的总数
                long totalCountForProduct = 0;

                for (Map.Entry<Integer, Map<String, Long>> entry : attitudeProductCountMap.entrySet()) {
                    Map<String, Long> countsForCurrentAttitude = entry.getValue();
                    if (countsForCurrentAttitude.containsKey(product)) {
                        totalCountForProduct += countsForCurrentAttitude.get(product);
                    }
                }
                // 计算当前用户态度在该产品下的记录数（即 countForCurrentAttitude）
                double percentage = totalCountForProduct > 0 ?
                        ((double)(countForCurrentAttitude * 100) / totalCountForProduct) : 0.0;
                // 格式化为小数点后两位
                String percentageFormatted = decimalFormat.format(percentage);

                // 创建新的 AttitudeData 对象并设置值
                FeedbackAnalysisResult.AttitudeData attitudeData = new FeedbackAnalysisResult.AttitudeData();
                attitudeData.setProduct(product);
                attitudeData.setPercentage(Double.valueOf(percentageFormatted));
                attitudeData.setLabelCount(countForCurrentAttitude);

                // 将 AttitudeData 添加到 ProductAttitude 的列表中
                productAttitude.getAttitudeData().add(attitudeData);
            }

            // 将 ProductAttitude 添加到最终列表中
            productAttitudes.add(productAttitude);
        }
        result.setProductAttitudeList(productAttitudes);


    }


    public void getUserAttitudeData(List<FeedbackAnalysisData> analysisDataList, FeedbackAnalysisResult result,
        Boolean showFirstLabel,Boolean showSecondLabel,Boolean showThreeLabel
    ) {

        // 根据布尔值确定分组的标签层级（优先级：三级 > 二级 > 一级）
        Function<FeedbackAnalysisData, String> labelClassifier;
        Predicate<FeedbackAnalysisData> labelFilter;

        if (showThreeLabel) {
            labelClassifier = FeedbackAnalysisData::getThreeLevelLabel;
            labelFilter = x -> StringUtils.isNotEmpty(x.getThreeLevelLabel());
        } else if (showSecondLabel) {
            labelClassifier = FeedbackAnalysisData::getSecondLevelLabel;
            labelFilter = x -> StringUtils.isNotEmpty(x.getSecondLevelLabel());
        } else if (showFirstLabel) {
            labelClassifier = FeedbackAnalysisData::getFirstLevelLabel;
            labelFilter = x -> StringUtils.isNotEmpty(x.getFirstLevelLabel());
        } else {
            // 默认回退到三级标签（如果所有开关都为 false）
            labelClassifier = FeedbackAnalysisData::getThreeLevelLabel;
            labelFilter = x -> StringUtils.isNotEmpty(x.getThreeLevelLabel());
        }

// 执行分组统计
        Map<String, Map<String, Map<Integer, Long>>> labelProductAttitudeCountMap = analysisDataList.stream()
                .filter(labelFilter)
                .collect(Collectors.groupingBy(
                        labelClassifier, // 动态选择标签层级
                        Collectors.groupingBy(
                                FeedbackAnalysisData::getProduct, // 按产品分组
                                Collectors.groupingBy(
                                        FeedbackAnalysisData::getUserAttitude, // 按用户态度分组
                                        LinkedHashMap::new,
                                        Collectors.summingLong(data ->
                                                data.getConsultCount() != null && data.getConsultCount() != 0 ?
                                                        data.getConsultCount() : 1
                                        )
                                )
                        )
                ));

        // 按标签分组
//        Map<String, Map<String, Map<Integer, Long>>> labelProductAttitudeCountMap = analysisDataList.stream()
//                .filter(x -> StringUtils.isNotEmpty(x.getThreeLevelLabel()))
//                .collect(Collectors.groupingBy(
//                        FeedbackAnalysisData::getThreeLevelLabel, // 按标签分组
//                        Collectors.groupingBy(
//                                FeedbackAnalysisData::getProduct, // 按产品分组
//                                Collectors.groupingBy(
//                                        FeedbackAnalysisData::getUserAttitude, // 按用户态度分组
//                                        LinkedHashMap::new,
//                                        Collectors.summingLong(data -> data.getConsultCount() != null && data.getConsultCount() != 0
//                                                ? data.getConsultCount() : 1)
//                                )
//                        )
//                ));

        // 遍历标签数据并填充结果
        for (Map.Entry<String, Map<String, Map<Integer, Long>>> labelEntry : labelProductAttitudeCountMap.entrySet()) {
            String label = labelEntry.getKey();
            FeedbackAnalysisResult.LabelAttitude labelAttitude = new FeedbackAnalysisResult.LabelAttitude();
            labelAttitude.setLabel(label);

            for (Map.Entry<String, Map<Integer, Long>> productEntry : labelEntry.getValue().entrySet()) {
                String product = productEntry.getKey();
                Map<Integer, Long> attitudeCountMap = productEntry.getValue();
                // 计算总数
                long total = attitudeCountMap.values().stream().mapToLong(Long::longValue).sum();
                // 填充用户态度数据
                FeedbackAnalysisResult.UserAttitudeData userAttitudeData = new FeedbackAnalysisResult.UserAttitudeData();
                userAttitudeData.setProduct(product);
                userAttitudeData.setAttitude("好");
                userAttitudeData.setPercentage(getPercentage(attitudeCountMap.getOrDefault(1, 0L), total));
                userAttitudeData.setLabelCount(attitudeCountMap.getOrDefault(1, 0L));
                labelAttitude.getUserAttitudeDataList().add(userAttitudeData);

                userAttitudeData = new FeedbackAnalysisResult.UserAttitudeData();
                userAttitudeData.setProduct(product);
                userAttitudeData.setAttitude("中");
                userAttitudeData.setPercentage(getPercentage(attitudeCountMap.getOrDefault(2, 0L), total));
                userAttitudeData.setLabelCount(attitudeCountMap.getOrDefault(2, 0L));
                labelAttitude.getUserAttitudeDataList().add(userAttitudeData);

                userAttitudeData = new FeedbackAnalysisResult.UserAttitudeData();
                userAttitudeData.setProduct(product);
                userAttitudeData.setAttitude("差");
                userAttitudeData.setPercentage(getPercentage(attitudeCountMap.getOrDefault(3, 0L), total));
                userAttitudeData.setLabelCount(attitudeCountMap.getOrDefault(3, 0L));
                labelAttitude.getUserAttitudeDataList().add(userAttitudeData);

                userAttitudeData = new FeedbackAnalysisResult.UserAttitudeData();
                userAttitudeData.setProduct(product);
                userAttitudeData.setAttitude("未表态");
                userAttitudeData.setPercentage(getPercentage(attitudeCountMap.getOrDefault(0, 0L), total));
                userAttitudeData.setLabelCount(attitudeCountMap.getOrDefault(0, 0L));
                labelAttitude.getUserAttitudeDataList().add(userAttitudeData);
            }
            result.getLabelAttitudeList().add(labelAttitude);

        }

        List<FeedbackAnalysisResult.Tag> list =result.getTrendTagList();

        // 提取 tagList 的 label 顺序
        List<String> tagLabelOrder = list.stream()
                .map(FeedbackAnalysisResult.Tag::getLabel)
                .collect(Collectors.toList());
        // 将 labelAttitudeList 转换为 Map，方便快速查找
//        Map<String, FeedbackAnalysisResult.LabelAttitude> labelAttitudeMap = result.getLabelAttitudeList().stream()
//                .collect(Collectors.toMap(FeedbackAnalysisResult.LabelAttitude::getLabel, item -> item));
        // 2.24日修改
        //合并重复键的数据
        //如果多个相同 label 的 LabelAttitude 需要合并（例如累加 labelCount 或合并 userAttitudeDataList），需在 toMap 中提供合并函数：
        Map<String, FeedbackAnalysisResult.LabelAttitude> labelAttitudeMap =
                result.getLabelAttitudeList().stream()
                        .collect(Collectors.toMap(
                                FeedbackAnalysisResult.LabelAttitude::getLabel, // Key: label
                                item -> item,                                   // Value: LabelAttitude 对象
                                (existing, replacement) -> {                   // 合并函数：处理重复键
                                    // 合并逻辑示例：合并 userAttitudeDataList
                                    existing.getUserAttitudeDataList().addAll(replacement.getUserAttitudeDataList());
                                    // 合并其他字段（如 allCount）
                                    existing.setAllCount((existing.getAllCount() == null ? 0 : existing.getAllCount()) + (replacement.getAllCount() == null ? 0 : replacement.getAllCount()));
                                    return existing;
                                }
                        ));


        // 拍成和tagList相同顺序
        result.setLabelAttitudeList(tagLabelOrder.stream()
                .map(labelAttitudeMap::get) // 根据 label 从 Map 中获取对应的 LabelAttitude
                .filter(Objects::nonNull)   // 过滤掉不存在的 label
                .collect(Collectors.toList()));

//        // 计算label总数
//        result.getLabelAttitudeList().forEach(i-> {
//                    // 计算 labelCount 的总和
//                    int totalLabelCount = 0;
//                    for (FeedbackAnalysisResult.UserAttitudeData element : i.getUserAttitudeDataList()) {
//                        totalLabelCount += element.getLabelCount();
//                    }
//                    i.setAllCount(totalLabelCount);
//                }
//        );
//        // 将labelCoont从大到小排序
//        List<FeedbackAnalysisResult.LabelAttitude> sortedList = result.getLabelAttitudeList().stream()
//                .sorted((o1, o2) -> {
//                    Integer count1 = o1.getAllCount();
//                    Integer count2 = o2.getAllCount();
//
//                    if (count1 == null && count2 == null) return 0;
//                    if (count1 == null) return 1;
//                    if (count2 == null) return -1;
//
//                    return count2.compareTo(count1);
//                })
//                .collect(Collectors.toList());
//        result.setLabelAttitudeList(sortedList);
    }

    private Integer getPercentage(Long count, long total) {
        return total == 0 ? 0 : (int) ((count * 100) / total);
    }


    // 将userAttitude转为对应的态度字符串
    private String getAttitudeLabel(Integer userAttitude) {
        switch (userAttitude) {
            case 1:
                return "好";
            case 2:
                return "中";
            case 3:
                return "差";
            case 0:
                return "未表态";
            default:
                return "未知";
        }
    }

    private static final String TEAM_UUID = "QspnyQrR";

    @Override
    public CommonResult<Boolean> saveFeedbackRecord(SaveFeedbackRecordParams param) {
        boolean result = false;
        long feedbackRecordId = 0L;
        // 新增逻辑
        if (param.getId() == 0L) {
            FeedbackRecord feedbackRecord = new FeedbackRecord();
            BeanUtils.copyProperties(param, feedbackRecord);
            //获取标签id
            StringBuilder builder = new StringBuilder();
            StringBuilder labelIdBuilder = new StringBuilder();
            String fileListString = String.join(",,,,", feedbackRecord.getFileList());
            param.getUserLabels().stream().forEach(x -> {
                FeedbackUserLabelRecord userLabelRecord = new FeedbackUserLabelRecord();
                userLabelRecord.setCreateTime(new Date());
                userLabelRecord.setUpdateTime(new Date());
                BeanUtils.copyProperties(x, userLabelRecord);
                feedbackUserLabelRecordMapper.insertSelective(userLabelRecord);
                builder.append(userLabelRecord.getId()).append(",");
                labelIdBuilder.append(userLabelRecord.getLabelId()).append(",");
            });
            if (builder.length() > 1) {
                builder.deleteCharAt(builder.length() - 1);
            }
            if (labelIdBuilder.length() > 1) {
                labelIdBuilder.deleteCharAt(labelIdBuilder.length() - 1);
            }
            feedbackRecord.setFileList(fileListString);
            feedbackRecord.setUserLabelIds(builder.toString());
            feedbackRecord.setLabelIds(labelIdBuilder.toString());
            feedbackRecord.setCreateTime(new Date());
            feedbackRecord.setUpdateTime(new Date());
            feedbackRecordMapper.insertSelective(feedbackRecord);
            feedbackRecordId = feedbackRecord.getId();
        } else {
            FeedbackRecord existRecord = feedbackRecordMapper.selectByPrimaryKey(param.getId());
            if (existRecord == null) {
                return CommonResult.Fail("未查询到已存在记录");
            }

            //删除剔除的
            StringBuilder deleteBuilder = new StringBuilder();
            if (!CollectionUtils.isEmpty(param.getUserLabels())) {
                List<Long> userLabelIds = param.getUserLabels().stream()
                        .filter(x -> x.getId() != 0)
                        .map(x -> x.getId())
                        .collect(Collectors.toList());
                if (StringUtils.isNotEmpty(existRecord.getUserLabelIds())) {
                    Arrays.stream(existRecord.getUserLabelIds().split(",")).forEach(x -> {
                        Optional<Long> optionalL = userLabelIds.stream().filter(y -> x.equals(y.toString())).findFirst();
                        if (!optionalL.isPresent()) {
                            deleteBuilder.append(x).append(",");
                        }
                    });
                }
            }
            if (deleteBuilder.length() > 1) {
                deleteBuilder.deleteCharAt(deleteBuilder.length() - 1);
                feedbackUserLabelRecordMapper.deleteByIds(deleteBuilder.toString().split(","));
            }

            //新增、更新
            BeanUtils.copyProperties(param, existRecord);
            String fileListString = String.join(",,,,", param.getFileList());
            existRecord.setFileList(fileListString);
            StringBuilder builder = new StringBuilder();
            StringBuilder labelIdBuilder = new StringBuilder();
            StringBuilder userAttitudeBuilder = new StringBuilder();
            param.getUserLabels().stream().forEach(x -> {
                String statusUuid = null;
                Date ticketTime = null;
                //ones状态同步
                if (StringUtils.isNotEmpty(x.getOnesId())) {
                    OnesUtil.TaskDetail taskDetail = OnesUtil.getTaskDetail(TEAM_UUID, x.getOnesId());
                    if (taskDetail != null) {
                        statusUuid = taskDetail.getStatus_uuid();
                        ticketTime = new Date(taskDetail.getServer_update_stamp() / 1000);
                    }
                }
                if (x.getId() == 0) {
                    //todo:待优化，批量处理
                    FeedbackUserLabelRecord userLabelRecord = new FeedbackUserLabelRecord();
                    userLabelRecord.setCreateTime(new Date());
                    userLabelRecord.setUpdateTime(new Date());
                    BeanUtils.copyProperties(x, userLabelRecord);
                    userLabelRecord.setTicketStatus(statusUuid);
                    userLabelRecord.setTicketTime(ticketTime);
                    feedbackUserLabelRecordMapper.insertSelective(userLabelRecord);
                    builder.append(userLabelRecord.getId()).append(",");
                    labelIdBuilder.append(userLabelRecord.getLabelId()).append(",");
                    userAttitudeBuilder.append(userLabelRecord.getUserAttitude()).append(",");
                } else {
                    FeedbackUserLabelRecord record = feedbackUserLabelRecordMapper.selectById(x.getId());
                    record.setComment(x.getComment());
                    record.setOnesId(x.getOnesId());
                    record.setUserAttitude(x.getUserAttitude());
                    record.setProblemId(x.getProblemId());
                    record.setUpdateTime(new Date());
                    record.setTicketStatus(statusUuid);
                    record.setTicketTime(ticketTime);
                    feedbackUserLabelRecordMapper.updateByPrimaryKeySelective(record);
                    builder.append(record.getId()).append(",");
                    labelIdBuilder.append(record.getLabelId()).append(",");
                    userAttitudeBuilder.append(record.getUserAttitude()).append(",");
                }
            });
            if (builder.length() > 1) {
                builder.deleteCharAt(builder.length() - 1);
            }
            if (labelIdBuilder.length() > 1) {
                labelIdBuilder.deleteCharAt(labelIdBuilder.length() - 1);
            }
            if (userAttitudeBuilder.length() > 1) {
                userAttitudeBuilder.deleteCharAt(userAttitudeBuilder.length() - 1);
            }
//            //类型不一致，赋值不成功
            existRecord.setReadMark(Integer.valueOf(param.getReadMark()));
            existRecord.setUserLabelIds(builder.toString());
            existRecord.setLabelIds(labelIdBuilder.toString());
            existRecord.setUserAttitude(userAttitudeBuilder.toString());
            existRecord.setUpdateTime(new Date());
            //更新到数据库
            feedbackRecordMapper.updateById(existRecord);
            feedbackRecordId = existRecord.getId();
        }

        //分析数据
        dealFeedbackAnalysisData(feedbackRecordId);

        return CommonResult.Success(true);
    }


    public void dealFeedbackAnalysisData(long feedbackRecordId) {
        //先删除
        feedbackAnalysisDataMapper.deleteByFeedbackRecordId(feedbackRecordId);
        //在增加
        FeedbackRecord feedbackRecord = feedbackRecordMapper.selectByPrimaryKey(feedbackRecordId);
        List<FeedbackUserLabelRecord> userLabelRecordList = feedbackUserLabelRecordMapper.selectUserLabelByIds(feedbackRecord.getUserLabelIds().split(","));
        String configIds = feedbackRecord.getConfigIds();
        if (!CollectionUtils.isEmpty(userLabelRecordList)) {
            String labelIds = userLabelRecordList.stream()
                    .filter(x -> x.getLabelId() != null)
                    .map(x -> x.getLabelId().toString())
                    .collect(Collectors.joining(","));
            if (StringUtils.isNotEmpty(labelIds)) {
                configIds = configIds + "," + labelIds;
            }
            String problemIdIds = userLabelRecordList.stream()
                    .filter(x -> x.getProblemId() != null)
                    .map(x -> x.getProblemId().toString())
                    .collect(Collectors.joining(","));
            if (StringUtils.isNotEmpty(problemIdIds)) {
                configIds = configIds + "," + problemIdIds;
            }
        }
        List<FeedbackConfig> configList = feedbackConfigMapper.selectByIds(configIds.split(","));
        List<FeedbackAnalysisData> feedbackAnalysisDataList = new ArrayList<>();
        userLabelRecordList.forEach(userLabel -> {
            FeedbackAnalysisData analysisData = new FeedbackAnalysisData();
            configList.forEach(config -> {
                if ("1".equals(config.getType())) {
                    analysisData.setBrand(config.getId().toString());
                }
                if ("2".equals(config.getType())) {
                    analysisData.setProduct(config.getId().toString());
                }
                if ("3".equals(config.getType())) {
                    analysisData.setStep(config.getId().toString());
                }
                if ("4".equals(config.getType())) {
                    analysisData.setSource(config.getId().toString());
                }if ("10".equals(config.getType())) {
                    analysisData.setCategory(config.getId().toString());
                }
                if (config.getId().equals(userLabel.getLabelId())) {
                    analysisData.setThreeLevelLabel(config.getId().toString());
                    //向上寻找一级和二级标签
                    FeedbackConfig secondCOnfig = feedbackConfigMapper.selectByPrimaryKey(config.getPid().longValue());
                    analysisData.setSecondLevelLabel(secondCOnfig.getId().toString());
                    FeedbackConfig firstConfig = feedbackConfigMapper.selectByPrimaryKey(secondCOnfig.getPid().longValue());
                    analysisData.setFirstLevelLabel(firstConfig.getId().toString());

                }
                if (config.getId().equals(userLabel.getProblemId())) {
                    analysisData.setProblemCatagory(config.getPid().toString());
                    analysisData.setProblem(config.getId().toString());
                }
            });
            analysisData.setUpdateTime(LocalDateTime.now());
            analysisData.setFeedbackRecordId(feedbackRecordId);
            analysisData.setOnesId(userLabel.getOnesId());
            analysisData.setTicketStatus(userLabel.getTicketStatus());
            //用户态度
            analysisData.setUserAttitude(Integer.valueOf(userLabel.getUserAttitude()));
            analysisData.setFeedbackTime(feedbackRecord.getFeedbackTime());
            feedbackAnalysisDataList.add(analysisData);
        });
        //批量插入
        if (!CollectionUtils.isEmpty(feedbackAnalysisDataList)) {
            feedbackAnalysisDataMapper.multiInsert(feedbackAnalysisDataList);
        }

    }


    @Override
    public CommonResult<Boolean> deleteFeedbackRecord(long id) {
        boolean Analysisflag =feedbackAnalysisDataMapper.deleteByFeedbackRecordId(id)>0;
        boolean Recordflag = feedbackRecordMapper.deleteByPrimaryKey(id) > 0;

        // 检查两个标志是否都为 true
        if (Recordflag) {
            return CommonResult.Success(true); // 两个删除操作都成功
        } else {
            return CommonResult.Fail("删除失败"); // 其中一个或两个操作失败
        }
//        return CommonResult.Success(feedbackRecordMapper.deleteByPrimaryKey(id) > 0);
    }

    @Override
    public CommonResult<String> multiUploadFile(MultipartFile[] files) {
        String path =null;
        String url = null;
        for (MultipartFile file : files) {
            if (file.getContentType().startsWith("image/")) {
                path = "FeedbackImage";
            }else if(file.getContentType().startsWith("video/")){
                path="FeedbackVideo";
            }else if(file.getContentType().equals("application/vnd.ms-excel") ||
                    file.getContentType().equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")){
                path="FeedbackExcel";
            }else if(file.getContentType().equals("application/vnd.ms-powerpoint") ||
                    file.getContentType().equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")
            ){
                path="FeedbackPPT";
            }
            try (InputStream stream = file.getInputStream()) {
                 url = openstorage.uploadFileNew(stream, "talkres", path, file.getOriginalFilename());  // 上传分片
            } catch (IOException e) {
                e.printStackTrace();
                return CommonResult.Fail("上传云存储报错");
            }
        }
        return CommonResult.Success(url);
    }

    public static final List<String> feedback_feild = Arrays.asList(new String[]{
            "id", "brand","category", "product", "feedbackContent", "consultCount", "likeCount", "viewCount", "feedbackSource", "feedbackTime",
            "feedbackUser", "feedbackStep", "feedbackType", "originalContent", "originalContentTime", "readMark", "threeLevelLabel", "userAttitude",
            "problem", "comment", "onesID"});

    @Transactional
    @Override
    public CommonResult<Boolean> importFeedbackData(MultipartFile file, String username) {
        boolean result = false;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/M/d");
        File dest = new File(EXCEL_PATH + file.getOriginalFilename());
        try {
            file.transferTo(dest);
        } catch (IOException e) {
//                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("上传失败。");
        }

        Workbook workbook = ExcelDealUtil.readExcel(dest);
        Sheet sheet1 = workbook.getSheetAt(0);
        List<FeedbackRecordDTO> feedbackRecordDTOList = ExcelDealUtil.readSheetConvertList(sheet1, feedback_feild, FeedbackRecordDTO.class);
        Optional<FeedbackRecordDTO> dtoOptional = feedbackRecordDTOList.stream()
                .filter(x -> StringUtils.isEmpty(x.getFeedbackContent())&& x.getId() == null)
                .findFirst();
        if (dtoOptional.isPresent()) {
            return CommonResult.Fail("反馈内容为必填项，该列有缺少！");
        }
        //查找品牌和型号
        String[] typeArr = {"1", "2", "3", "4", "5", "6", "7", "8", "9","10"};
        List<FeedbackConfig> configList = feedbackConfigMapper.selectByTypes(typeArr);
        List<FeedbackAnalysisData> feedbackAnalysisDataList = new ArrayList<>();
        Map<String, List<FeedbackRecordDTO>> feedbackRecordDTOMap = feedbackRecordDTOList.stream().collect(Collectors.groupingBy(FeedbackRecordDTO::getId));
        for (Map.Entry<String, List<FeedbackRecordDTO>> entry : feedbackRecordDTOMap.entrySet()) {
            List<FeedbackRecordDTO> newFeedbackRecordDTOList = entry.getValue();
            StringBuilder userLabelRecordIdBuilder = new StringBuilder();
            StringBuilder labelIdBuilder = new StringBuilder();
            for (FeedbackRecordDTO dto : newFeedbackRecordDTOList) {
                FeedbackUserLabelRecord userLabelRecord = dealUserLabelRecord(configList, dto);
                if (userLabelRecord != null) {
                    userLabelRecordIdBuilder.append(userLabelRecord.getId()).append(",");
                    if (userLabelRecord.getLabelId() != 0) {
                        labelIdBuilder.append(userLabelRecord.getLabelId()).append(",");
                    }
                }
            }
            if (userLabelRecordIdBuilder.length() > 1) {
                userLabelRecordIdBuilder.deleteCharAt(userLabelRecordIdBuilder.length() - 1);
            }
            if (labelIdBuilder.length() > 1) {
                labelIdBuilder.deleteCharAt(labelIdBuilder.length() - 1);
            }
            newFeedbackRecordDTOList = newFeedbackRecordDTOList.stream()
                    .filter(x -> StringUtils.isNotEmpty(x.getFeedbackContent()))
                    .collect(Collectors.toList());
            for (FeedbackRecordDTO dto : newFeedbackRecordDTOList) {
                dealFeedbackRecord(configList, dto, username, formatter, feedbackAnalysisDataList,
                        userLabelRecordIdBuilder.toString(), labelIdBuilder.toString());
            }

        }

        //批量插入
        if (!CollectionUtils.isEmpty(feedbackAnalysisDataList)) {
            result = feedbackAnalysisDataMapper.multiInsert(feedbackAnalysisDataList) > 0;
        }
        return CommonResult.Success(result);
    }

    public FeedbackUserLabelRecord dealUserLabelRecord(List<FeedbackConfig> configList, FeedbackRecordDTO dto) {
        FeedbackConfig labelConfig = configList.stream()
                .filter(x -> "7".equals(x.getType()) && x.getName().equals(dto.getThreeLevelLabel()))
                .findFirst()
                .orElse(null);
        if (labelConfig == null) {
            return null;
        }
        FeedbackUserLabelRecord userLabelRecord = new FeedbackUserLabelRecord();
        userLabelRecord.setLabelId(labelConfig.getId());
        userLabelRecord.setUserAttitude(StringUtils.isNotEmpty(dto.getUserAttitude()) ? String.valueOf(Dictionary.USER_ATTITUDE.fromName(dto.getUserAttitude())) : null);
        userLabelRecord.setComment(dto.getComment());
        userLabelRecord.setOnesId(dto.getOnesID());
        String statusUuid = null;
        Date ticketTime = null;
        //ones状态同步
        if (StringUtils.isNotEmpty(dto.getOnesID())) {
            OnesUtil.TaskDetail taskDetail = OnesUtil.getTaskDetail(TEAM_UUID, dto.getOnesID());
            if (taskDetail != null) {
                statusUuid = taskDetail.getStatus_uuid();
                ticketTime = new Date(taskDetail.getServer_update_stamp() / 1000);
            }
        }
        userLabelRecord.setTicketStatus(statusUuid);
        userLabelRecord.setTicketTime(ticketTime);
        FeedbackConfig problemConfig = configList.stream()
                .filter(x -> "9".equals(x.getType()) && x.getName().equals(dto.getProblem()))
                .findFirst()
                .orElse(null);
        userLabelRecord.setProblemId(problemConfig == null ? null : problemConfig.getId());
        userLabelRecord.setCreateTime(new Date());
        userLabelRecord.setUpdateTime(new Date());

        feedbackUserLabelRecordMapper.insertSelective(userLabelRecord);
        return userLabelRecord;
    }

    public void dealFeedbackRecord(List<FeedbackConfig> configList, FeedbackRecordDTO dto, String username,
                                   DateTimeFormatter formatter, List<FeedbackAnalysisData> feedbackAnalysisDataList,
                                   String userLabelIds, String labelIds) {
        StringBuilder builder = new StringBuilder();
        FeedbackConfig brandConfig = configList.stream()
                .filter(x -> "1".equals(x.getType()) && x.getName().equals(dto.getBrand()))
                .findFirst()
                .orElse(null);
        FeedbackConfig productConfig = configList.stream()
                .filter(x -> "2".equals(x.getType()) && x.getName().equals(dto.getProduct()))
                .findFirst()
                .orElse(null);
        FeedbackConfig categoryConfig = configList.stream()
                .filter(x -> "10".equals(x.getType()) && x.getName().equals(dto.getCategory()))
                .findFirst()
                .orElse(null);
        FeedbackConfig stepConfig = configList.stream()
                .filter(x -> "3".equals(x.getType()) && x.getName().equals(dto.getFeedbackStep()))
                .findFirst()
                .orElse(null);
        FeedbackConfig sourceConfig = configList.stream()
                .filter(x -> "4".equals(x.getType()) && x.getName().equals(dto.getFeedbackSource()))
                .findFirst()
                .orElse(null);
        if (brandConfig != null) {
            builder.append(brandConfig.getId()).append(",");
        }
        if (categoryConfig != null) {
            builder.append(categoryConfig.getId()).append(",");
        }
        if (productConfig != null) {
            builder.append(productConfig.getId()).append(",");
        }
        if (stepConfig != null) {
            builder.append(stepConfig.getId()).append(",");
        }
        if (sourceConfig != null) {
            builder.append(sourceConfig.getId());
        }

        Integer attitudeValue = null; // 使用 Integer 对象类型以便可以赋值为 null
        // 判断 dto.getUserAttitude() 的值并赋值
        if (dto.getUserAttitude() == null || dto.getUserAttitude().isEmpty()) {
            // 如果为空或不存在，保持 attitudeValue 为 null
            attitudeValue = 0;
        } else if ("好".equals(dto.getUserAttitude())) {
            attitudeValue = 1; // "好" 对应的值为 1
        } else if ("中".equals(dto.getUserAttitude())) {
            attitudeValue = 2; // "中" 对应的值为 2
        } else if ("差".equals(dto.getUserAttitude())) {
            attitudeValue = 3; // "差" 对应的值为 3
        } else {
            attitudeValue = 0; // 未表态或其他情况对应的值为 0
        }

        // 判断结尾是否有逗号，并去除
        if (builder.length() > 0 && builder.charAt(builder.length() - 1) == ',') {
            builder.deleteCharAt(builder.length() - 1);
        }
        FeedbackRecord feedbackRecord = new FeedbackRecord()
                .setConfigIds(builder.toString())
                .setUserLabelIds(userLabelIds)
                .setLabelIds(labelIds)
                .setUserAttitude(String.valueOf(attitudeValue))
                .setFeedbackContent(dto.feedbackContent)
                .setConsultCount(StringUtils.isEmpty(dto.consultCount) ? 0 : Integer.valueOf(dto.consultCount))
                .setLikeCount(StringUtils.isEmpty(dto.likeCount) ? 0 : Integer.valueOf(dto.likeCount))
                .setViewCount(StringUtils.isEmpty(dto.viewCount) ? 0 : Integer.valueOf(dto.viewCount))
                .setReadMark(0)
                .setFeedbackUser(dto.getFeedbackUser())
                .setFeedbackTime(StringUtils.isEmpty(dto.getFeedbackTime()) ? null : parseDate(dto.getFeedbackTime()))
                .setFeedbackType("主动反馈".equals(dto.feedbackType) ? 0 : 1)
                .setOriginalContent(dto.originalContent)
                .setOriginalContentTime(StringUtils.isEmpty(dto.getOriginalContentTime()) ? null : LocalDate.parse(dto.getOriginalContentTime(), formatter))
                .setRecorder(username)
                .setCreateTime(new Date())
                .setUpdateTime(new Date());
        feedbackRecordMapper.insertSelective(feedbackRecord);
        if (StringUtils.isNotEmpty(userLabelIds)) {
            Arrays.stream(userLabelIds.split(",")).forEach(x -> {
                FeedbackUserLabelRecord feedbackUserLabelRecord = feedbackUserLabelRecordMapper.selectById(Long.parseLong(x));
                FeedbackConfig threeLabelConfig = configList.stream()
                        .filter(y -> y.getId().equals(feedbackUserLabelRecord.getLabelId()))
                        .findFirst()
                        .orElse(null);
                FeedbackConfig secondLabelConfig = configList.stream()
                        .filter(y -> y.getId().equals(threeLabelConfig.getPid()))
                        .findFirst()
                        .orElse(null);
                FeedbackConfig problemConfig = configList.stream()
                        .filter(y -> y.getId().equals(feedbackUserLabelRecord.getProblemId()))
                        .findFirst()
                        .orElse(null);
                if (threeLabelConfig != null) {

                    FeedbackAnalysisData analysisData = new FeedbackAnalysisData();
                    if (brandConfig != null) {
                        analysisData.setBrand(brandConfig.getId().toString());
                    }
                    if (categoryConfig != null) {
                        analysisData.setCategory(categoryConfig.getId().toString());
                    }
                    if (productConfig != null) {
                        analysisData.setProduct(productConfig.getId().toString());
                    }
                    if (stepConfig != null) {
                        analysisData.setStep(stepConfig.getId().toString());
                    }
                    if (sourceConfig != null) {
                        analysisData.setSource(sourceConfig.getId().toString());
                    }
                    analysisData.setFeedbackRecordId(feedbackRecord.getId())
                            .setFirstLevelLabel(secondLabelConfig.getPid().toString())
                            .setSecondLevelLabel(threeLabelConfig.getPid().toString())
                            .setThreeLevelLabel(feedbackUserLabelRecord.getLabelId().toString())
                            .setUserAttitude(Integer.valueOf(feedbackUserLabelRecord.getUserAttitude()))
                            .setProblemCatagory(problemConfig == null ? null : problemConfig.getPid().toString())
                            .setProblem(feedbackUserLabelRecord.getProblemId() == null ? null : feedbackUserLabelRecord.getProblemId().toString())
                            .setOnesId(feedbackUserLabelRecord.getOnesId())
                            .setTicketStatus(feedbackUserLabelRecord.getTicketStatus())
                            .setFeedbackTime(feedbackRecord.getFeedbackTime())
                            .setUpdateTime(LocalDateTime.now());
                    if (brandConfig != null && productConfig != null && stepConfig != null && sourceConfig != null) {
                        feedbackAnalysisDataList.add(analysisData);
                    }
                }
            });
        }
//        feedbackRecordList.add(feedbackRecord);
    }

    private static LocalDate parseDate(String dateString) {
        // 尝试的格式
        String[] patterns = {
                "yyyy/M/d",
                "yyyy-M-d",
                "yyyy年M月d日"
        };

        for (String pattern : patterns) {
            try {
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
                return LocalDate.parse(dateString, formatter);
            } catch (DateTimeParseException ignored) {
                log.error("日期解析出错："+ignored.getMessage());
            }
        }
        return null;
    }

    @Data
    public static class FeedbackRecordDTO {
        private String id;
        private String brand;
        private String category;
        private String product;
        private String feedbackContent;
        private String consultCount;
        private String likeCount;
        private String viewCount;
        private String feedbackSource;
        private String feedbackTime;
        private String feedbackUser;
        private String feedbackStep;
        private String feedbackType;
        private String originalContent;
        private String originalContentTime;
        private String readMark;
        private String threeLevelLabel;
        private String userAttitude;
        private String problem;
        private String comment;
        private String onesID;
    }
}
